GensLimts = require "packages/lang/GensLimts"
local AIinit require "packages/lang/AI/init"
local LU = require "packages/lang/LUltiity"
local U = require "packages/utility/utility"
local WU = require "packages/wdtx/WUltiity"
--------------------------------修改、覆盖某些卡牌的函数逻辑-----------------------------------------
Fk.skills["nullification_skill"].onUse = function(self, room, effect)
  room:delay(120)
  if room.current.id < 0 then
    -- local timeout = room.timeout
    -- room.timeout = 3
    local invokeplayer = table.find(room.alive_players,function(pr) return pr.id > 0 end) or room.alive_players[1]
    room:askForSkillInvoke(invokeplayer, "invokebynulli", nil, "#invokebynulli") --操蛋delay，其他人响应delay尤其是人机会减少dely时间造成秒出牌。所以给玩家一个询问，停止delay
    -- room:notifySkillInvoked(room.current, "invokebynulli", "control")
    -- room.timeout = timeout
  end
end
Fk:loadTranslationTable{
  ["invokebynulli"] ="无懈暂停",
  ["#invokebynulli"] = "当前回合角色如果是人机即可弹出此中断询问防止无懈后人机秒出牌问题。",
}
--------------------------------修改、覆盖某些卡牌的函数逻辑-----------------------------------------

--------------------------------此处修改、覆盖游戏核心类的函数---------------------------------------
--玩家类修改
function Player:getTableMark(mark)
  local mark = self.mark[mark]
  if type(mark) == "table" then return table.simpleClone(mark) end
  return {}
end

--卡牌类修改
function Card:getTableMark(mark)
  local ret = self:getMark(mark)
  return type(ret) == "table" and ret or {}
end

--房间类修改
local Room = require "server.room"
function Room:cleanProcessingArea(cards, skillName)
  local throw = cards and table.filter(cards, function(id) return self:getCardArea(id) == Card.Processing end) or self.processing_area
  if #throw > 0 then
    self:moveCardTo(throw, Card.DiscardPile, nil, fk.ReasonPutIntoDiscardPile, skillName)
  end
end
function Room:invalidateSkill(player, skill_name, temp)
  temp = temp and temp or ""
  self:addTableMark(player, MarkEnum.InvalidSkills .. temp, skill_name)
end
function Room:validateSkill(player, skill_name, temp)
  temp = temp and temp or ""
  self:removeTableMark(player, MarkEnum.InvalidSkills .. temp, skill_name)
end
function Room:addTableMark(sth, mark, value)
  local t = sth:getTableMark(mark)
  table.insert(t, value)
  if sth:isInstanceOf(Card) then
    self:setCardMark(sth, mark, t)
  else
    self:setPlayerMark(sth, mark, t)
  end
end
function Room:removeTableMark(sth, mark, value)
  local t = sth:getTableMark(mark)
  table.removeOne(t, value)
  if sth:isInstanceOf(Card) then
    self:setCardMark(sth, mark, #t > 0 and t or 0)
  else
    self:setPlayerMark(sth, mark, #t > 0 and t or 0)
  end
end

---@return boolean
local function execGameEvent(tp, ...)
  local event = tp:create(...)
  local _, ret = event:exec()
  return ret
end
---@param cardEffectEvent CardEffectEvent
function Room:handleCardEffect(event, cardEffectEvent)
  if event == fk.PreCardEffect then
    if cardEffectEvent.card.skill:aboutToEffect(self, cardEffectEvent) then return end
    if
      cardEffectEvent.card.trueName == "slash" and
      not (cardEffectEvent.unoffsetable or table.contains(cardEffectEvent.unoffsetableList or Util.DummyTable, cardEffectEvent.to))
    then
      local loopTimes = 1
      if cardEffectEvent.fixedResponseTimes then
        if type(cardEffectEvent.fixedResponseTimes) == "table" then
          loopTimes = cardEffectEvent.fixedResponseTimes["jink"] or 1
        elseif type(cardEffectEvent.fixedResponseTimes) == "number" then
          loopTimes = cardEffectEvent.fixedResponseTimes
        end
      end
      Fk.currentResponsePattern = "jink"

      for i = 1, loopTimes do
        local to = self:getPlayerById(cardEffectEvent.to)
        local prompt = ""
        if cardEffectEvent.from then
          if loopTimes == 1 then
            prompt = "#slash-jink:" .. cardEffectEvent.from
          else
            prompt = "#slash-jink-multi:" .. cardEffectEvent.from .. "::" .. i .. ":" .. loopTimes
          end
        end

        local use = self:askForUseCard(
          to,
          "jink",
          nil,
          prompt,
          true,
          nil,
          cardEffectEvent
        )
        if use then
          use.toCard = cardEffectEvent.card
          use.responseToEvent = cardEffectEvent
          self:useCard(use)
        end

        if not cardEffectEvent.isCancellOut then
          break
        end

        cardEffectEvent.isCancellOut = i == loopTimes
      end
    elseif
      cardEffectEvent.card.type == Card.TypeTrick and
      not (cardEffectEvent.disresponsive or cardEffectEvent.unoffsetable) and
      not table.contains(cardEffectEvent.prohibitedCardNames or Util.DummyTable, "nullification")
    then
      local players = {}
      Fk.currentResponsePattern = "nullification"
      local cardCloned = Fk:cloneCard("nullification")
      for _, p in ipairs(self.alive_players) do
        if not p:prohibitUse(cardCloned) then
          local cards = p:getHandlyIds()
          for _, cid in ipairs(cards) do
            if
              Fk:getCardById(cid).trueName == "nullification" and
              not (
                table.contains(cardEffectEvent.disresponsiveList or Util.DummyTable, p.id) or
                table.contains(cardEffectEvent.unoffsetableList or Util.DummyTable, p.id)
              )
            then
              table.insert(players, p)
              break
            end
          end
          if not table.contains(players, p) then
            Self = p -- for enabledAtResponse
            for _, s in ipairs(table.connect(p.player_skills, p._fake_skills)) do
              if
                s.pattern and
                Exppattern:Parse("nullification"):matchExp(s.pattern) and
                not (s.enabledAtResponse and not s:enabledAtResponse(p)) and
                not (
                  table.contains(cardEffectEvent.disresponsiveList or Util.DummyTable, p.id) or
                  table.contains(cardEffectEvent.unoffsetableList or Util.DummyTable, p.id)
                )
              then
                table.insert(players, p)
                break
              end
            end
          end
        end
      end

      local prompt = ""
      if cardEffectEvent.to then
        prompt = "#AskForNullification::" .. cardEffectEvent.to .. ":" .. cardEffectEvent.card.name
      elseif cardEffectEvent.from then
        prompt = "#AskForNullificationWithoutTo:" .. cardEffectEvent.from .. "::" .. cardEffectEvent.card.name
      end

      local extra_data
      if #TargetGroup:getRealTargets(cardEffectEvent.tos) > 1 then
        local parentUseEvent = self.logic:getCurrentEvent():findParent(GameEvent.UseCard)
        if parentUseEvent then
          extra_data = { useEventId = parentUseEvent.id, effectTo = cardEffectEvent.to }
        end
      end
      local use = self:askForNullification(players, nil, nil, prompt, true, extra_data, cardEffectEvent)
      if use then
        use.toCard = cardEffectEvent.card
        use.responseToEvent = cardEffectEvent
        self:useCard(use)
      end
    end
    Fk.currentResponsePattern = nil
  elseif event == fk.CardEffecting then
    if cardEffectEvent.card.skill then
      execGameEvent(GameEvent.SkillEffect, function ()
        cardEffectEvent.card.skill:onEffect(self, cardEffectEvent)
      end, self:getPlayerById(cardEffectEvent.from), cardEffectEvent.card.skill)
    end
  end
end

--- 将一些卡牌同时分配给一些角色。
---@param room Room @ 房间
---@param list table<integer[]> @ 分配牌和角色的数据表，键为角色id，值为分配给其的牌id数组
---@param proposer? integer @ 操作者的id。默认为空
---@param skillName? string @ 技能名。默认为“分配”
---@return table<integer[]> @ 返回成功分配的卡牌
function Room:doYiji(room, list, proposer, skillName)
  if not skillName then --兼容有些扩展包作者带room参数，另一些不带room
    skillName = proposer
    proposer = list
    list = room
    room = self
  end
  skillName = skillName or "distribution_skill"
  local moveInfos = {}
  local move_ids = {}
  for to, cards in pairs(list) do
    local toP = room:getPlayerById(to)
    local handcards = toP:getCardIds("h")
    cards = table.filter(cards, function (id) return not table.contains(handcards, id) end)
    if #cards > 0 then
      table.insertTable(move_ids, cards)
      local moveMap = {}
      local noFrom = {}
      for _, id in ipairs(cards) do
        local from = room.owner_map[id]
        if from then
          moveMap[from] = moveMap[from] or {}
          table.insert(moveMap[from], id)
        else
          table.insert(noFrom, id)
        end
      end
      for from, _cards in pairs(moveMap) do
        table.insert(moveInfos, {
          ids = _cards,
          moveInfo = table.map(_cards, function(id)
            return {cardId = id, fromArea = room:getCardArea(id), fromSpecialName = room:getPlayerById(from):getPileNameOfId(id)}
          end),
          from = from,
          to = to,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonGive,
          proposer = proposer,
          skillName = skillName,
        })
      end
      if #noFrom > 0 then
        table.insert(moveInfos, {
          ids = noFrom,
          to = to,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonGive,
          proposer = proposer,
          skillName = skillName,
        })
      end
    end
  end
  if #moveInfos > 0 then
    room:moveCards(table.unpack(moveInfos))
  end
  return move_ids
end
--room抽象类
function AbstractRoom:isGameMode(mode)
  return self.room_settings.gameMode == mode
end
function Room:isGameMode(mode)
  return self.settings.gameMode == mode
end

--Uitlity工具修改
U.CardNameBox = function(spec)
  return UI.ComboBox(spec)
end
------------------------------此处修改、覆盖游戏核心类的函数------------------------------------

------------------------------此扩展的diy武将，启动--------------------------------------------
local extension = Package("lang")
Fk:loadTranslationTable{
    ["lang"] = "浪系列",
    ["l"] = "浪"
}
--幻想风车
local hxfc_author = General(extension, "hxfc_author", "wei", 1)
Fk:loadTranslationTable{
  ["hxfc_author"] = "幻想风车",
}
--马超
local l__machao = General(extension, "l__machao", "shu", 4)
local l_zongqiang = fk.CreateTriggerSkill{
  name = "l_zongqiang",
  -- frequency = Skill.Compulsory,
  anim_type = "offensive",
  events = {fk.DamageCaused,fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) or player ~= target then return end
    if event == fk.DamageCaused then
      return player:getMark("l_zongqiang_damage-turn") == 0 and data.card and (data.card.trueName == "slash" or data.card.trueName == "duel")
    else
      return player:getMark("l_zongqiang_see-turn") == 0 and (data.card.trueName == "slash" or data.card.trueName == "duel")
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.DamageCaused then
      local atkrange = player:getAttackRange() - 1
      local hands = player:getCardIds("he")
      if atkrange > 0 and #hands > 0 then
        local cards = room:askForDiscard(player,atkrange,atkrange,true,self.name,true,".","#l_zongqiang_promt:::"..atkrange..":"..atkrange)
        if #cards == atkrange then
          self.cost_data = atkrange
          return true
        end        
      end
    else
      local to = room:getPlayerById(data.to)
      return #to.player_cards[Player.Hand] > 0
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.DamageCaused then
      data.damage = data.damage + self.cost_data
      room:addPlayerMark(player,"l_zongqiang_damage-turn")
    else
      U.viewCards(player, room:getPlayerById(data.to):getCardIds(Player.Hand), self.name, "$ViewCardsFrom:"..data.to)
      room:addPlayerMark(player,"l_zongqiang_see-turn")
    end
  end,
}
local l_jinyi = fk.CreateTriggerSkill{
  name = "l_jinyi",
  anim_type = "control",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) or player:usedSkillTimes(self.name, Player.HistoryTurn) ~= 0 or #player:getMark("l_jinyi_selchc") == 0 then return end
    local cards = {}
    for _, move in ipairs(data) do
      if move.toArea == Card.DiscardPile then
        for _, info in ipairs(move.moveInfo) do
          if Fk:getCardById(info.cardId).type == Card.TypeEquip and
            table.contains(player.room.discard_pile, info.cardId) then
            table.insertIfNeed(cards, info.cardId)
          end
        end
      end
    end
    cards = U.moveCardsHoldingAreaCheck(player.room, cards)
    if #cards > 0 then
      self.cost_data = cards
      return true
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local cards = table.clone(self.cost_data)

    local selequip
    if #cards == 1 then
      selequip = Fk:getCardById(cards[1])
    else
      selequip = U.askforChooseCardsAndChoice(player, cards, {"OK"}, self.name, "#l_jinyi-choose_equip")[1]
      if not selequip then selequip = cards[1] end
      selequip = Fk:getCardById(selequip)
    end

    local _, dat = room:askForUseActiveSkill(player, "l_jinyi_active", "#l_jinyi_active-invoke:::"..selequip:toLogString(), true)
    if dat and dat.targets and #dat.targets > 0 then
      self.cost_data = {selequip = selequip.id, seltar = dat.targets[1],selchs = dat.interaction}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local seltar = self.cost_data.seltar
    local selequip = self.cost_data.selequip
    local selchs = self.cost_data.selchs
    local equip = Fk:getCardById(selequip)
    local tar = room:getPlayerById(seltar)
    if tar ~= player then
      U.moveCardIntoEquip(room, tar, {selequip}, self.name, true, player)
    else
      if not player:getEquipment(equip.sub_type) then
        U.moveCardIntoEquip(room, tar, {selequip}, self.name, true, player)
      end
    end
    if not selchs or selchs == "" or tar == player then return end

    if selchs == "equipsuit" then
      -- local tarcards = table.filter(tar.player_cards[Player.Hand],function(cid) return Fk:getCardById(cid).suit == equip.suit end)
      -- room:obtainCard(player.id, tarcards,true,fk.ReasonJustMove)
      local ret
      local suit = equip.suit
      if suit == Card.Spade then
        ret = "♠"
      elseif suit == Card.Heart then
        ret = "♥"
      elseif suit == Card.Club then
        ret = "♣"
      elseif suit == Card.Diamond then
        ret = "♦"
      end
      if ret then
        room:setPlayerMark(tar,"@usecardsuit-turn",ret)
        room:setPlayerMark(tar,"cardsuit-turn",suit)
      end
    elseif selchs == "equipword" then
      local tarhands = tar.player_cards[Player.Hand]
      if #tarhands == 0 then return end
      local n = Fk:translate(equip.trueName, "zh_CN"):len()
      local selcards = room:askForCardsChosen(player, tar,1,math.min(n,#tarhands),"h", self.name)
      room:obtainCard(player.id, selcards,true,fk.ReasonJustMove)
    elseif selchs == "getotherequips" then
      local otherequips = table.filter(tar.player_cards[Player.Equip],function(cid) return cid ~= selequip end)
      if #otherequips > 0 then
        room:obtainCard(player.id, otherequips,true,fk.ReasonJustMove)
      end
    elseif selchs == "drawgenskills" then
      local skills = table.filter(tar.player_skills,function(s) return s:isPlayerSkill(tar) end)
      if #skills > 0 then
        room:drawCards(player,#skills,self.name)
      end
      room:addPlayerMark(tar,"@@l_jinyi-turn")
      room:addPlayerMark(tar, MarkEnum.UncompulsoryInvalidity .. "-turn")
    end
    local selchc = player:getMark("l_jinyi_selchc")
    local remchc = player:getMark("l_jinyi_remchc")
    table.removeOne(selchc,selchs)
    table.insert(remchc,selchs)
    room:setPlayerMark(player,"l_jinyi_selchc",selchc)
    room:setPlayerMark(player,"l_jinyi_remchc",remchc)
  end,
  refresh_events = {fk.EventAcquireSkill,fk.RoundStart,fk.Death},
  can_refresh = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill then
      return player == target and self == data
    elseif event == fk.RoundStart then
      return player:hasSkill(self)
    else
      return player:hasSkill(self) and data.damage and data.damage.from and data.damage.from == player and #player:getMark("l_jinyi_remchc") > 0
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventAcquireSkill then
      room:setPlayerMark(player,"l_jinyi_selchc",{"equipsuit","equipword","getotherequips","drawgenskills"})
      room:setPlayerMark(player,"l_jinyi_remchc",{})
    else
      local remchc = player:getMark("l_jinyi_remchc")
      if #remchc > 0 then
        room:notifySkillInvoked(player, self.name, "special")
        local chs = room:askForChoice(player, remchc, self.name,"#l_jinyi_recchc")
        local selchc = player:getMark("l_jinyi_selchc")
        table.insert(selchc,chs)
        table.removeOne(remchc,chs)
        room:setPlayerMark(player,"l_jinyi_selchc",selchc)
        room:setPlayerMark(player,"l_jinyi_remchc",remchc)
      end
    end
  end
}
local l_jinyi_prohibit = fk.CreateProhibitSkill{
  name = "#l_jinyi_prohibit",
  prohibit_use = function(self, player, card)
    if player:getMark("cardsuit-turn") > 0 then
      return card.suit ~= player:getMark("cardsuit-turn")
    end
  end,
  prohibit_response = function(self, player, card)
    if player:getMark("cardsuit-turn") > 0 then
      return card.suit ~= player:getMark("cardsuit-turn")
    end
  end,
}
l_jinyi:addRelatedSkill(l_jinyi_prohibit)
local l_jinyi_active = fk.CreateActiveSkill{
  name = "l_jinyi_active",
  card_num = 0,
  target_num = 1,
  interaction = function()
    local jinyi_chc = Self:getMark("l_jinyi_selchc")
    if jinyi_chc ~= 0 and #jinyi_chc > 0 then
      return UI.ComboBox {choices = table.clone(jinyi_chc)}
    end
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    local jinyi_chc = Self:getMark("l_jinyi_selchc")
    if jinyi_chc == 0 or #jinyi_chc == 0 then
      return #selected == 0
    else
      return #selected == 0 and to_select ~= Self.id
    end
  end,
}
Fk:addSkill(l_jinyi_active)
l__machao:addSkill(l_zongqiang)
l__machao:addSkill(l_jinyi)
Fk:loadTranslationTable{
  ["l__machao"] = "马超",
  ["l_zongqiang"] = "纵枪",
  ["#l_zongqiang_promt"] = "你可以弃 %arg 张牌令伤害+ %arg2 ",
  [":l_zongqiang"] = "当你每回合第一次使用【杀】或【决斗】指向目标时观看目标手牌，当你使用【杀】或【决斗】对其造成伤害则可弃X张牌伤害+X（X为攻击范围-1，限1次）",

  ["l_jinyi"] = "锦衣",
  ["@@l_jinyi-turn"] = "非所技能失效",
  ["#l_jinyi-choose_equip"] = "锦衣：选择你要置入的1张装备牌",
  ["l_jinyi_active"] = "锦衣",
  ["#l_jinyi_prohibit"] = "锦衣",
  ["equipsuit"] = "本回合其只能使用或打出此装备花色手牌",
  ["equipword"] = "获得其此卡字数手牌",
  ["getotherequips"] = "获得其装备区除此卡的其他装备",
  ["drawgenskills"] = "摸武将技能数牌并使其本回合非锁技能失效",
  ["@usecardsuit-turn"] = "只能使用",
  ["#l_jinyi_recchc"] = "你可以恢复1个被移除的选项。",
  ["#l_jinyi_active-invoke"] = "锦衣：你可以选择一名角色将 %arg 置入其装备栏。若有此技能选项可从中选1满足条件项获得其牌（或摸牌）",
  [":l_jinyi"] = "每回合限1次，当有装备牌进入弃牌区你可以将其中1张装备置入其他角色（若此技能选项都被移除可置入自己）装备区，你从以下选项可选1项然后移除:<br/>1.本回合其只能使用或打出此装备花色手牌<br/>2.获得其此装备牌字数的手牌<br/>3.获得其装备区除此装备的其他装备<br/>4.摸其武将技能数的牌且此回合非锁技能失效<br/>每轮开始或每当你杀死一名角色时你可以恢复一个被移除选项。",

}
--荀彧
local l__xunyu = General(extension, "l__xunyu", "wei", 3)
local l_fujie = fk.CreateTriggerSkill{
  name = "l_fujie",
  -- frequency = Skill.Compulsory,
  anim_type = "control",
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = room:getNCards(1)
    room:moveCards({
      ids = cards,
      toArea = Card.Processing,
      moveReason = fk.ReasonJustMove,
      skillName = self.name,
      proposer = player.id,
    })
    local card = Fk:getCardById(cards[1])
    local tars = room:askForChoosePlayers(player,table.map(room.alive_players,function(pr) return pr.id end),1,1,"#l_fujie-choose:::"..card:toLogString(),self.name,false)
    local tar = room:getPlayerById(tars[1])
    room:obtainCard(tar.id, card,true,fk.ReasonJustMove)
    if card.type == Card.TypeTrick then
      if not player:hasSkill("ol_ex__jieming") then
        room:handleAddLoseSkills(player, "ol_ex__jieming", nil, false)
      end
    elseif card.type == Card.TypeEquip then
      local amazing_grace = Fk:cloneCard("amazing_grace")
      amazing_grace.skillName = self.name
      local tos = {}
      for _, pr in ipairs(room.alive_players) do
        if not player:isProhibited(pr, amazing_grace) then
          table.insert(tos,{pr.id})
        end
      end
      if #tos == 0 then return end
      room:useCard({
        card = amazing_grace,
        from = player.id,
        tos = tos,
        skillName = self.name,
        extraUse = true,
      })
    end
  end,
  refresh_events = {fk.BeforeCardUseEffect},
  can_refresh = function(self, event, target, player, data)
    return target == player and not player.dead and data.card.trueName == "amazing_grace" and data.card.skillName == self.name
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local sortplayers = room:getOtherPlayers(player)
    table.insert(sortplayers,1,player)
    local tos = table.map(sortplayers,function(pr) return {pr.id} end)
    data.tos = tos
  end
}
local l_wangzuo = fk.CreateTriggerSkill{
  name = "l_wangzuo",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and not player:isNude()
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local cards = player:getCardIds("he")
    local discs = room:askForDiscard(player,1,#cards,true,self.name,true,".","#l_wangzuo_promt")
    if #discs > 0 then
      self.cost_data = discs
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player,"@l_wangzuo-phase",math.min(#self.cost_data,3))
    if #self.cost_data >= 3 then
      WU:checkCards(player,".|.|.|.|.|trick",1)
    end
  end,
}
local l_wangzuo_delay = fk.CreateTriggerSkill{
  name = "#l_wangzuo_delay",
  -- frequency = Skill.Compulsory,
  events = {fk.CardUsing, fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) or target ~= player or not data.card:isCommonTrick() then return end
    if event == fk.CardUsing then
      return player:getMark("@l_wangzuo-phase") >= 1
    else
      return player:getMark("@l_wangzuo-phase") >= 2 and #player.room:getUseExtraTargets(data) > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(l_wangzuo.name)
    if event == fk.CardUsing then
      data.disresponsiveList = table.map(room.alive_players, Util.IdMapper)
    else
      local targets = room:getUseExtraTargets(data)
      if #targets == 0 then return false end
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#l_wangzuo-choose:::"..data.card:toLogString(), l_wangzuo.name, true)
      if #tos > 0 then
        table.forEach(tos, function (id)
          table.insert(data.tos, {id})
        end)
      end
    end
  end,
}
l_wangzuo:addRelatedSkill(l_wangzuo_delay)
l__xunyu:addSkill(l_fujie)
l__xunyu:addSkill(l_wangzuo)
Fk:loadTranslationTable{
  ["l__xunyu"] = "荀彧",
  ["l_fujie"] = "辅节",
  ["#l_fujie-choose"] = "令一名角色获得 %arg",
  [":l_fujie"] = "当你受到伤害时，展示牌堆一张牌并令一名角色获得，若该牌为锦囊牌，你获得“节命”，若为装备牌，视为你使用【五谷丰登】",
  ["l_wangzuo"] = "王佐",
  ["#l_wangzuo_delay"] = "王佐",
  ["#l_wangzuo-choose"] = "王佐：你可以为%arg额外指定一个目标",
  ["@l_wangzuo-phase"] = "王佐 ",
  ["#l_wangzuo_promt"] = "弃置X张牌获得以下效果：1.使用普通锦囊牌无法被响应;2.使用普通锦囊牌可额外选择一个目标;3.从牌堆中获得一张随机锦囊牌",
  [":l_wangzuo"] = "出牌阶段开始时时你可以弃置任意张牌，触发以下效果；1.使用普通锦囊牌无法被响应。2.使用普通锦囊牌时，可额外选择一个目标。3.从牌堆中获得一张随机锦囊牌",
}

local l__qianxun = fk.CreateTriggerSkill{
  name = "l__qianxun",
  frequency = Skill.Compulsory,
  anim_type = "control",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.type == Card.TypeTrick and (not player:isNude() or not player.room.current:isNude())
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if not player:isNude() and not player.dead then
      room:askForDiscard(player,1,1,true,self.name,false)
    end
    if not room.current:isNude() and not room.current.dead then
      room:askForDiscard(room.current,1,1,true,self.name,false)
    end
  end
}
local l__youjin = fk.CreateTriggerSkill{
  name = "l__youjin",
  anim_type = "drawcard",
  -- frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if player:isKongcheng() then
        for _, move in ipairs(data) do
          if move.from == player.id then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerHand then
                return true
              end
            end
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local handleSkillCard = function(who,isprohibit)
      if who.dead then return end
      local getids = room:drawCards(who,1,self.name)
      if getids and #getids > 0 and isprohibit then
        local card = Fk:getCardById(getids[1])
        room:setCardMark(card,"@@youjin-inhand-turn",1)
      end
    end
    handleSkillCard(player,false)
    handleSkillCard(room.current,player ~= room.current)
  end,
}
local youjin_prohibit = fk.CreateProhibitSkill{
  name = "#youjin_prohibit",
  prohibit_use = function(self, player, card)
    return card:getMark("@@youjin-inhand-turn") == 1
  end,
  prohibit_response = function(self, player, card)
    return card:getMark("@@youjin-inhand-turn") == 1
  end,
  prohibit_discard = function(self, player, card)
    return card:getMark("@@youjin-inhand-turn") == 1
  end,
}
local l__kedi = fk.CreateViewAsSkill{
  name = "l__kedi",
  pattern = ".",
  anim_type = "special",
  interaction = function()
    local names = {}
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id)
      if (card.type == Card.TypeBasic or card:isCommonTrick()) and not card.is_derived and
      ((Fk.currentResponsePattern == nil and Self:canUse(card)) or
      (Fk.currentResponsePattern and Exppattern:Parse(Fk.currentResponsePattern):match(card))) then
        table.insertIfNeed(names, card.name)
      end
    end
    if #names == 0 then return false end
    return UI.ComboBox { choices = names }
  end,
  card_filter = function(self, to_select, selected)
    local card = Fk:getCardById(to_select)
    return card:getMark("@@kedi-inhand-turn") == 1
  end,
  view_as = function(self, cards)
    if #cards == 0 then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and table.every(Self:getCardIds(Player.Hand),function(cid) return Fk:getCardById(cid):getMark("@@kedi-inhand-turn") == 1 end)
  end,
  enabled_at_response = function(self, player, response)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and table.every(Self:getCardIds(Player.Hand),function(cid) return Fk:getCardById(cid):getMark("@@kedi-inhand-turn") == 1 end)
  end,
}
local kedi_trig = fk.CreateTriggerSkill{
  name = "#kedi_trig",
  -- anim_type = "drawcard",
  -- frequency = Skill.Compulsory,
  refresh_events = {fk.AfterCardsMove},
  can_refresh = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    local room = player.room
    for _, move in ipairs(data) do
      if move.to == player.id and move.toArea == Player.Hand then
        self.cost_data = {}
        for _, info in ipairs(move.moveInfo) do
          table.insert(self.cost_data,info.cardId)
        end
        return true
      end
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    for _,cid in ipairs(self.cost_data) do
      local card = Fk:getCardById(cid)
      room:setCardMark(card,"@@kedi-inhand-turn",1)
    end
  end
}
l__youjin:addRelatedSkill(youjin_prohibit)
l__kedi:addRelatedSkill(kedi_trig)
local l__luxun = General(extension, "l__luxun", "wu", 3)
l__luxun:addSkill(l__qianxun)
l__luxun:addSkill(l__youjin)
l__luxun:addSkill(l__kedi)
Fk:loadTranslationTable{
  ["l__luxun"] = "陆逊",
  ["l__qianxun"] = "谦逊",
  [":l__qianxun"] = "锁定技，当你成为锦囊牌的目标后，弃置你与当前回合角色各1张牌。",
  ["l__youjin"] = "诱进",
  ["#youjin_prohibit"] = "诱进",
  ["@@youjin-inhand-turn"] = "诱进",
  [":l__youjin"] = "当你失去最后一张手牌后，你可以与当前回合角色各摸1张牌，其他角色以此法获得的牌本回合不能使用，打出或弃置。",
  ["l__kedi"] = "克敌",
  ["#kedi_trig"] = "克敌",
  ["@@kedi-inhand-turn"] = "克敌",
  [":l__kedi"] = "每回合限一次，当你需要使用牌时，若你仅有本回合获得的手牌，则你可以将任意张手牌当做一张基本牌或普通锦囊牌使用。",
}
--祝融
local xiangzhen = fk.CreateTriggerSkill{
  name = "l_xiangzhen",
  anim_type = "support",
  frequency = Skill.Compulsory,
  refresh_events = {fk.CardUseFinished},
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(self) and data.card and data.card.trueName == "savage_assault"
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if data.damageDealt then
      room:notifySkillInvoked(player, self.name, "special")
      local damagenum = 0
      for id, v in pairs(data.damageDealt) do
        damagenum = damagenum + 1
      end
      local choices = {"xiangzhendraw:::"..damagenum,"xiangzhendisc:::"..damagenum}
      local chs = room:askForChoice(player, choices, self.name)
      if string.startsWith(chs,"xiangzhendraw") then
        room:drawCards(player,damagenum,self.name)
      else
        local ret = room:askForDiscard(player,damagenum,damagenum,true,self.name,true)
        if ret and #ret > 0 then
          room:useVirtualCard("savage_assault", nil, player, room:getOtherPlayers(player), self.name, true)
        end
      end
    end
  end
}
local invokeManYongSkill = function(player,skiname)
  local room = player.room
  room:notifySkillInvoked(player, skiname, "special")
  room:addPlayerMark(player,"@forever_dc_add",1)
  local mansiids = player:getMark("mansiids")
  mansiids = mansiids == 0 and {} or mansiids
  if #mansiids > 0 then
    for _, pid in ipairs(mansiids) do
      local tar = room:getPlayerById(pid)
      room:handleAddLoseSkills(tar, "-mansi", nil, false)
    end
  end
  local tars = {}
  for _, pr in ipairs(room.alive_players) do
    if pr ~= player and not pr:hasSkill("mansi") then
      table.insert(tars,pr.id)
    end
  end
  local seltars = room:askForChoosePlayers(player,tars,1,1,"#manyong_choose",skiname,true)
  if seltars and #seltars > 0 then
    local tar = room:getPlayerById(seltars[1])
    table.insertIfNeed(mansiids,seltars[1])
    room:setPlayerMark(player,"mansiids",mansiids)
    room:handleAddLoseSkills(tar, "mansi", nil, false)
  end
end
local manyong = fk.CreateTriggerSkill{
  name = 'manyong',
  -- anim_type = "negative",
  priority = 0.01,
  refresh_events = {fk.DrawNCards,fk.RoundEnd},
  can_refresh = function(self, event, target, player, data)
    if event == fk.RoundEnd then
      local room = player.room
      if player:hasSkill(self) then
        local savainto_disc = false
        room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
          for _,info in ipairs(e.data) do
            if info.toArea and info.toArea == Card.DiscardPile and table.find(info.moveInfo,function(cinfo) return Fk:getCardById(cinfo.cardId).trueName == "savage_assault" end) then
              savainto_disc = true
              return
            end
          end
        end, Player.HistoryRound)
        return not savainto_disc
      end
    else
      return player:hasSkill(self) and player == target and player:getMark("@forever_dc_add") > 0
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.RoundEnd then
      invokeManYongSkill(player,self.name)
    else
      room:notifySkillInvoked(player, self.name, "drawcard")
      data.n = data.n + player:getMark("@forever_dc_add")
    end 
  end,
}
local l__zhurong = General(extension, "l__zhurong", "shu", 4,4,2)
l__zhurong:addSkill(xiangzhen)
l__zhurong:addSkill(manyong)
Fk:loadTranslationTable{
  ["l__zhurong"] = "祝融",
  ["l_xiangzhen"] = "象阵",
  ["xiangzhendraw"] = "摸%arg张牌",
  ["xiangzhendisc"] = "弃置%arg张牌，视为使用一张【南蛮入侵】",
  [":l_xiangzhen"] = "锁定技，每当有【南蛮入侵】结算结束，你选择：1、摸x张牌; 2、弃置x张牌，视为使用一张【南蛮入侵】。（x为该南蛮入侵造成的伤害，至少为1触发。）",
  ["manyong"] = "蛮勇",
  ["@forever_dc_add"] = "永久摸牌+",
  ["#manyong_choose"] = "选择一名其他角色，令在下一轮内获得“蛮嗣”。",
  [":manyong"] = "每轮结束时，若该轮内没有【南蛮入侵】进入弃牌堆，你摸牌数永久+1，并选择一名其他角色，令在下一轮内获得“蛮嗣”。",
}

--浪张绣
local l__zhangxiu = General(extension, "l__zhangxiu", "qun", 4)
local l_luanxiong = fk.CreateActiveSkill{
  name = "l_luanxiong",
  anim_type = "offensive",
  target_num = 1,
  -- frequency = Skill.Limited,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    local room = Fk:currentRoom()
    local target = room:getPlayerById(to_select)
    local tarsmark = Self:getMark("l_luanxiong_tars")
    if #selected == 0 then
      if Self.id == to_select and Self:getMark("l_luanxiong_self") == 0 then
          return true
      end
      if Self.id ~= to_select then
        return tarsmark == 0 or not table.contains(tarsmark,to_select) 
      end
    end 
  end,
  on_use = function(self, room, effect)
    local to = room:getPlayerById(effect.tos[1])
    local player = room:getPlayerById(effect.from)
    local eqipSlots = to:getAvailableEquipSlots()
    if not table.contains(to.sealedSlots, Player.JudgeSlot) then
      table.insert(eqipSlots, Player.JudgeSlot)
    end
    room:abortPlayerArea(to, eqipSlots)
    local targetRecorded = type(player:getMark("l_luanxiong_tars")) == "table" and player:getMark("l_luanxiong_tars") or {}
    if player.id == to.id then
      room:setPlayerMark(player,"l_luanxiong_self",1)
      if #targetRecorded == 0 then return end
      room:doAnimate("InvokeUltSkill", {name = self.name,player = player.id})
      for _,pid in ipairs(targetRecorded) do
        local tar = room:getPlayerById(pid)
        room:setPlayerMark(tar,"@@l_luanxiong_tar",1)
      end
    else
      table.insertIfNeed(targetRecorded, to.id)
      room:setPlayerMark(player, "l_luanxiong_tars", targetRecorded)
      room:setPlayerMark(to, "l_luanxiong_useslash", 1)
      while true do
        if to.dead then return end
        local use = room:askForUseCard(to, "slash", "slash", "l_luanxiong_slash::"..player.id, true, {must_targets = {player.id}, bypass_distances = true})
        if use then
          room:useCard(use)
        else
          room:setPlayerMark(to, "l_luanxiong_useslash", 0)
          break
        end
      end
    end
  end,
}
local l_luanxiong_filter = fk.CreateFilterSkill{
  name = "#l_luanxiong_filter",
  card_filter = function(self, to_select, player)
    if player:getMark("l_luanxiong_useslash") > 0 then
      return to_select.type == Card.TypeBasic 
    end
  end,
  view_as = function(self, to_select, player)
    return Fk:cloneCard("slash", to_select.suit, to_select.number)
  end,
}
local l_luanxiong_tri = fk.CreateTriggerSkill{
  name = "#l_luanxiong_tri",
  -- anim_type = "",
  frequency = Skill.Compulsory,
  events = {fk.DamageCaused},
  can_trigger = function (self, event, target, player, data) 
    if player:hasSkill(self) and data.card and data.card.trueName == "slash" and data.to and data.to == player then
      if data.from and data.from:getMark("l_luanxiong_useslash") == 1 and player:getMark("l_luanxiong_tars") ~= 0 and table.contains(player:getMark("l_luanxiong_tars"),data.from.id) then
        self.cost_data = "slash_adddamage"
        return true
      end
      if player:getMark("damage_reduce") == 1 then
        return true
      end
    end
    return 
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local damage = player:getMark("damage_add")
    local reduce = player:getMark("damage_reduce")
    data.damage = data.damage + damage - reduce
    if self.cost_data and self.cost_data == "slash_adddamage" and data.damage > 0 then
      room:addPlayerMark(player,"damage_add",1)
      self.cost_data = nil
    end
    if reduce == 1 then
      room:setPlayerMark(player,"damage_reduce",0)
    end
  end,
  refresh_events = {fk.TurnEnd},
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(self.name) and target == player and (player:getMark("damage_add") > 0 or player:getMark("l_luanxiong_self") == 1)
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if player:getMark("damage_add") > 0 then
      room:setPlayerMark(player,"damage_add",0)
    end
    if player:getMark("l_luanxiong_self") == 1 then
      for _,pr in ipairs(room.players) do
        if pr:getMark("@@l_luanxiong_tar") == 1 then --"@@l_luanxiong_tar",1
          room:setPlayerMark(pr,"@@l_luanxiong_tar",0)
        end
      end
    end
  end
}
local l_luanxiong_prohibit = fk.CreateProhibitSkill{
  name = "#l_luanxiong_prohibit",
  prohibit_use = function(self, player, card)
    if player:getMark("@@l_luanxiong_tar") > 0 then
      local subcards = card:isVirtual() and card.subcards or {card.id}
      return #subcards > 0 and table.every(subcards, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
  prohibit_response = function(self, player, card)
    if player:getMark("@@l_luanxiong_tar") > 0 then
      local subcards = card:isVirtual() and card.subcards or {card.id}
      return #subcards > 0 and table.every(subcards, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
}
local l_luanxiong_targetmod = fk.CreateTargetModSkill{
  name = "#l_luanxiong_targetmod",
  bypass_times = function(self, player, skill, scope, card, to)
    if card and to and to:getMark("@@l_luanxiong_tar") > 0 then
      local targetRecorded = player:getMark("l_luanxiong_tars")
      return type(targetRecorded) == "table" and table.contains(targetRecorded, to.id)
    end
  end,
  bypass_distances = function(self, player, skill, card, to)
    if card and to and to:getMark("@@l_luanxiong_tar") > 0 then
      local targetRecorded = player:getMark("l_luanxiong_tars")
      return type(targetRecorded) == "table" and table.contains(targetRecorded, to.id)
    end
  end,
}
local l_hengqiang = fk.CreateTriggerSkill{
  name = "l_hengqiang",
  -- anim_type = "",
  -- frequency = Skill.Compulsory,
  events = {fk.TargetSpecifying},
  can_trigger = function (self, event, target, player, data) 
    return player:hasSkill(self) and data.card and not data.card:isVirtual() and data.from and data.card.trueName == "slash" and data.to == player.id
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local patstr = ".|.|.|.|.|^basic"
    local discard = room:askForCard(player, 1, 1, true, self.name, true, patstr, "#l_hengqiang_nobasic")
    if discard and #discard > 0 then self.cost_data = discard[1] return true end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player,"damage_reduce",1)
    room:obtainCard(player.id, data.card,true,fk.ReasonJustMove)
    room:obtainCard(data.from,self.cost_data,true,fk.ReasonJustMove)
  end,
}
local l_juehen = fk.CreateTriggerSkill{
  name = "l_juehen",
  events = {fk.TurnStart,fk.EnterDying},
  can_trigger = function (self, event, target, player, data)  
    if not player:hasSkill(self) then return end
    if event == fk.TurnStart then
      -- if player.room.current.id ~= player.id then
      return (#player.room.current:getAvailableEquipSlots() ~= 5 or table.contains(player.room.current.sealedSlots, Player.JudgeSlot)) and #player.room.current:getCardIds("he") > 0 and table.find(player.room:getOtherPlayers(player.room.current),function(p) return #p:getAvailableEquipSlots() == 5 and not table.contains(p.sealedSlots, Player.JudgeSlot) end)
      -- end
    else
      return (#target:getAvailableEquipSlots() ~= 5 or table.contains(target.sealedSlots, Player.JudgeSlot)) 
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      local patstr = ".|.|.|.|.|^basic"
      local others = table.filter(room:getOtherPlayers(target),function(p) return #p:getAvailableEquipSlots() == 5 and not table.contains(p.sealedSlots, Player.JudgeSlot) end)
      local rettars,retcard = room:askForChooseCardAndPlayers(target,table.map(others,function(p) return p.id end), 1, 1,patstr, "#l_juehen_nobasic",self.name,true)
      if #rettars > 0 and retcard then self.cost_data = {rettars[1],retcard} return true end
    else 
      return true
    end
   
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TurnStart then
      if self.cost_data then
        -- local tar = room:getPlayerById(self.cost_data[1])
        room:obtainCard(self.cost_data[1],self.cost_data[2],true,fk.ReasonJustMove)
        local choices = table.simpleClone(target.sealedSlots)
        local choice = room:askForChoice(target, choices, self.name, "#l_juehen_resume")
        room:resumePlayerArea(target, {choice})
      end
      self.cost_data = nil
    else
      local resumes = table.simpleClone(target.sealedSlots)
      room:resumePlayerArea(target, resumes)
      room:drawCards(target,#resumes,self.name)
    end
  end,
}
l_luanxiong:addRelatedSkill(l_luanxiong_targetmod)
l_luanxiong:addRelatedSkill(l_luanxiong_prohibit)
l_luanxiong:addRelatedSkill(l_luanxiong_tri)
l_luanxiong:addRelatedSkill(l_luanxiong_filter)
l__zhangxiu:addSkill(l_luanxiong)
l__zhangxiu:addSkill(l_hengqiang)
l__zhangxiu:addSkill(l_juehen)
Fk:loadTranslationTable{
  ["l__zhangxiu"] = "张绣",
  ["l_luanxiong"] = "绝恨",
  ["#l_luanxiong_tri"] = "绝恨",
  ["#l_luanxiong_filter"] = "绝恨",
  ["#l_luanxiong_prohibit"] = "绝恨",
  ["#l_luanxiong_targetmod"] = "绝恨",
  ["@@l_luanxiong_tar"] = "绝恨",
  ["#l_juehen_resume"] = "乱雄：回复1个废除区域",
  ["#l_juehen_nobasic"] = "是否交个其他角色1张非基本牌恢复1个废除区域",
  ["#l_hengqiang_nobasic"] = "是否用1张非基本牌交换指向你的【杀】",
  ["l_luanxiong_slash"] = "是否对 %dest 出杀",
  ["#l_hengqiang_delay"] = "寒枪",
  [":l_luanxiong"] = "每名角色限一次，你于出牌阶段可以废除一名角色的装备区和判定区，若不为你，其可以将一张基本牌当造成伤害+X的【杀】对你使用，该流程可重复。若为你，则本回合你对以此法选择过的其他角色使用牌无距离次数限制，且该角色本回合不可使用或打出手牌。（X为其本回合使用杀的次数-1）",
  ["l_hengqiang"] = "寒枪",
  [":l_hengqiang"] = "当你成为其他角色使用非虚拟【杀】的目标后，你可以交给其一张非基本牌，然后此【杀】伤害-1且你获得之。",
  ["l_juehen"] = "乱雄",
  [":l_juehen"] = "每个角色回合开始时，若其有废除的装备栏或判定区，其可以交给其他区域未废除角色一张非基本牌，然后恢复一个废除的装备栏或判定区。当有角色进入濒死状态时，其恢复所有废除区并摸恢复的装备栏与判定区总和的牌。",
  ["$l_luanxiong1"] = "北地枭雄，乱世不败！！",
  ["$l_luanxiong2"] = "雄据宛城，虽乱世可安！",
  ["~l__zhangxiu"] = "若失文和……吾将何归……",
}

--潘多拉宝箱
--吞噬
local l_tunshi = fk.CreateTriggerSkill{
    name = "l_tunshi",
    -- anim_type = "",
    frequency = Skill.Compulsory,
    events = {fk.CardUseFinished,fk.TargetConfirming},
    can_trigger = function (self, event, target, player, data) 
      if not player:hasSkill(self.name) then return end
      if event ==fk.TargetConfirming then
          return player.phase == Player.NotActive and data.to == player.id and data.from ~= player.id and math.random() < 0.4
      else
          return player.phase == Player.NotActive and target ~= player and data.card and math.random() < 0.4
      end
    end,
    on_use = function(self, event, target, player, data)
      local room = player.room
      if event ==fk.TargetConfirming then
        AimGroup:cancelTarget(data, data.to)
      else
        local targethands = target:getCardIds{Player.Hand, Player.Equip}
        if #targethands > 0 then
            local randc = table.random(targethands)
            room:obtainCard(player.id,randc,true,fk.ReasonJustMove)
            local card = Fk:getCardById(randc)
            if card.type == Card.TypeTrick then
                  room:damage{
                  from = player,
                  to = target,
                  damage = 1,
                  skillName = self.name,
                }
            end
            if card.type == Card.TypeBasic then
                room:changeMaxHp(player, 1)
            end
        end
      end
      
     end,
}
local obtreasure = {shenqi = 0.2,skill = 0.15,draw=0.3,none = 0.35}
local l_caibao = fk.CreateTriggerSkill{
    name = "l_caibao",
    -- anim_type = "",
    frequency = Skill.Compulsory,
    events = {fk.Damaged,fk.EventPhaseStart},
    can_trigger = function (self, event, target, player, data) 
      if player == target and player:hasSkill(self.name) then
        if event == fk.Damaged then
          return data.from 
        else
          return player.phase == Player.Start
        end
      end
    end,
    on_use = function(self, event, target, player, data)
      local room = player.room
      if event == fk.EventPhaseStart then
        local hands = player:getCardIds{ Player.Hand }
        if #hands < player.maxHp then
          room:drawCards(player,player.maxHp - #hands,self.name)
        end
        player:skip(Player.Judge)
        player:skip(Player.Draw)
        player:skip(Player.Discard)
        return
      end
      local endlPrac = room.logic.endlPrac
      if not endlPrac then room:doBroadcastNotify("ShowToast", "不是巅峰神塔模式得不到我的东西。嘿嘿~") return end
      local randChoice = function (cfg,num)
        local choices = {} 
        while #choices < num do
          local rand = math.random()
          local forward = 0
          for i, v in pairs(cfg) do
            local last = v
            if rand >= forward and rand < last + forward  then
              table.insert(choices,i)
              break
            end
            forward = forward + last
          end
        end
        return choices
      end
      local rand = randChoice(obtreasure,1)[1]
      -- local rand = "shenqi"
      if rand == "shenqi" then
        local shenqi = endlPrac:getPyGodWeapon()
        if #shenqi == 0 then room:doBroadcastNotify("ShowToast", "浦元的神器被榨干了...") return end
        local isget
        local randsq = table.random(shenqi)
        endlPrac:removePyGodWeapon("st_"..randsq)
        local name = randsq
        for _, id in ipairs(Fk:getAllCardIds()) do
          local card = Fk:getCardById(id, true)
          if card.trueName == name then
            isget = true
            room:obtainCard(data.from,id,true,fk.ReasonJustMove)
            break
          end
        end
        if isget then
          room:doBroadcastNotify("ShowToast", "潘多拉吐了一把"..Fk:translate(randsq).."。"..Fk:translate(player.general) .."获得浦元的神器")
        else
          room:doBroadcastNotify("ShowToast", "找不到浦元的神器，似乎忘了开扩展包？")
        end
      elseif rand == "draw" then
        local num = table.random({1,2,3})
        room:drawCards(data.from,num,self.name)
        room:doBroadcastNotify("ShowToast", "潘多拉不耐烦吐了"..num.."张牌给"..Fk:translate(player.general))
      elseif rand == "skill" then
        if endlPrac.getpdlskillnum >= 7 then 
          room:doBroadcastNotify("ShowToast", "贪得无厌。欸嘿嘿~")
          local losehp = math.ceil(player.hp / 3)
          room:loseHp(data.from,losehp,self.name)
          room:loseHp(player,99,self.name)
          return
        end
        if endlPrac.all_generals and #endlPrac.all_generals > 0 then
          local getRandSkills = function (rands_n,all_generals,who)
            local getskills_t = {}
            local trans_skinames = ""
            while #getskills_t < rands_n do
              local randg = table.random(all_generals)
              local skills_name = {}
              for _, ski in ipairs(randg.skills) do
                if ski.frequency < Skill.Limited then
                  table.insert(skills_name,ski.name)
                end
              end
              if #skills_name > 0 then
                local rand_skill = table.random(skills_name)
                local skilltrueName = Fk.skills[rand_skill].trueName
                local canget = table.every(who.player_skills,function (ski)
                  if ski.trueName ~= skilltrueName then
                    return true
                  end
                end)
                if canget then
                  if #trans_skinames > 0 then
                    trans_skinames = trans_skinames.. "、"
                  end
                  trans_skinames = trans_skinames..Fk:translate(rand_skill)
                  table.insert(getskills_t,rand_skill)
                end
              end
            end
            local skills = table.concat(getskills_t,"|")
            skills = string.sub(skills,1,-1)
            room:handleAddLoseSkills(who, skills, nil, false)
            room:doBroadcastNotify("ShowToast",Fk:translate(who.general).."获得技能："..trans_skinames)
          end
          getRandSkills(1,endlPrac.all_generals,data.from)
          endlPrac.getpdlskillnum = endlPrac.getpdlskillnum + 1
        else
          room:drawCards(data.from ,3,self.name)
        end
      else
        room:doBroadcastNotify("ShowToast",Fk:translate(player.general).."并没有从潘多拉拿到什么...")
      end
     end,
}
local l__panduola = General(extension,"l__panduola","qun",15)
l__panduola:addSkill(l_tunshi)
l__panduola:addSkill(l_caibao)

Fk:loadTranslationTable{
    ["l__panduola"] = "潘多拉",
    ["l_tunshi"] = "吞噬",
    [":l_tunshi"] = "锁定技，其他角色使用牌指向你时，你有概率取消之。其他角色使用牌后，你有概率随机获得对面一张牌，若获得的牌为基本牌你最大体力+1，若为锦囊牌你对其造成1点伤害",
    ["l_caibao"] = "宝藏",
    [":l_caibao"] = "锁定技，准备阶段你把手牌摸到体力上限并跳过除出牌阶段其他所有阶段，当你受到伤害时，你有概率令伤害来源获得某种东西（对巅峰神塔有效否则都为摸牌）",
}
--吕布
local l_wushuang = fk.CreateTriggerSkill{
  name = "l_wushuang",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player and table.contains({ "slash", "duel" }, data.card.trueName)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    data.fixedResponseTimes = data.fixedResponseTimes or {}
    if data.card.trueName == "slash" then
      local jink_mark = player:getMark("l_wushuang_sha")
      if jink_mark == 0 then
        data.fixedResponseTimes["jink"] = 4 - #data.tos[1]
        room:setPlayerMark(player,"l_wushuang_sha",data.fixedResponseTimes["jink"])
      else
        data.fixedResponseTimes["jink"] = jink_mark
      end
      if #data.tos[1] == 1 and data.to == data.tos[1][1] then
        room:setPlayerMark(player,"l_wushuang_sha",0)
      end
      return
    else
        data.fixedAddTimesResponsors = data.fixedAddTimesResponsors or {}
        table.insert(data.fixedAddTimesResponsors, data.to)
        local mark = player:getMark("l_wushuang_duel")
      if mark == 0 then
        
        data.fixedResponseTimes["slash"] = 4 - #data.tos[1]
      else
        data.fixedResponseTimes["slash"] = mark
        if #data.tos[1] == 1 and data.to == data.tos[1][1] then
          room:setPlayerMark(player,"l_wushuang_duel",0)
          return
        end
      end
    end

    if data.card.trueName == "duel" and player:getMark("l_wushuang_duel") == 0 then
      local fiterother = table.filter(room:getOtherPlayers(player),function (p)
        if p.id ~= data.to then
            return true
        end
      end)
      if #fiterother == 0 then 
        room:setPlayerMark(player,"l_wushuang_duel",0)
        return 
      end
      local pids = room:askForChoosePlayers(player,table.map(fiterother,function (p) return p.id end),0,2,"#l_wushuang_invoke",self.name,true)
      
      if #pids > 0 then
        table.forEach(pids, function(pid)
            -- AimGroup:addTargets(room, data, pid)
            TargetGroup:pushTargets(data.targetGroup, pid)
            -- table.insert(data.fixedAddTimesResponsors, pid)
            table.insert(data.tos[1], pid)
        end)         
        data.fixedResponseTimes["slash"] = data.fixedResponseTimes["slash"] - #pids
        room:setPlayerMark(player,"l_wushuang_duel",data.fixedResponseTimes["slash"])
      end
    end
  end,
}

local l_wushuang_tarmod = fk.CreateTargetModSkill{
  name = "#l_wushuang_tarmod",
  extra_target_func = function(self, player, skill)
    if skill.trueName == "slash_skill" and player:hasSkill("l_wushuang") then
      return 2
    end
  end,
}

local l_wumou = fk.CreateTriggerSkill{
  name = "l_wumou",
--   anim_type = "control",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove,fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return end
    if event == fk.AfterCardsMove then
      for _, move in ipairs(data) do
        if move.to and move.to == player.id and move.toArea and move.toArea == Card.PlayerHand then
          local trick_cards = {}               
          for _, info in ipairs(move.moveInfo) do
            local card = Fk:getCardById(info.cardId)
            if card and card.type == Card.TypeTrick then
              table.insert(trick_cards,info.cardId)
            end
          end
          if #trick_cards > 0 then
            self.cost_data = trick_cards               
            return true
          end
        end
      end
    else           
      return target.phase == Player.Start
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local handcard = function (cids,name)
      table.forEach(cids,function(cid)
        local card = Fk:getCardById(cid,true)
        if card.type == Card.TypeTrick then
          room:setCardMark(card,"use_duel_slash",name)               
        end
      end)
    end
    if player.phase ~= Player.NotActive then
      if event == fk.AfterCardsMove then
        if not self.cost_data then return end
        handcard(self.cost_data,"duel")
      else
        handcard(player.player_cards[Player.Hand],"duel")
      end
    else
      if event == fk.AfterCardsMove then
        if not self.cost_data then return end
        handcard(self.cost_data,"slash")
      else
        handcard(player.player_cards[Player.Hand],"slash")
      end
    end
    self.cost_data = nil
  end,
}

local l_wumou_duel_slash = fk.CreateFilterSkill{
  name = "#l_wumou_duel_slash",
  card_filter = function(self, card, player)
    if player:hasSkill(self.name) and card.type == Card.TypeTrick and card:getMark("use_duel_slash") ~= 0 then
      return true
    end
  end,
  view_as = function(self, card) 
    local c = Fk:cloneCard(card:getMark("use_duel_slash"), card.suit, card.number)
    c.skillName = self.name
    return c
  end,
}

local l_wuqian = fk.CreateTriggerSkill{
  name = "l_wuqian",
  anim_type = "offensive",
  events = {fk.TargetConfirming},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and data.to == player.id and data.from ~= data.to and data.card and data.card.trueName == "slash"
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local user = room:getPlayerById(data.from)
    local use = room:askForUseCard(player, "slash", "slash", "l_wuqian_slash::"..data.from, true, {must_targets = {data.from}, bypass_distances = true})
    if use then
      room:useCard(use)
    end
  end,
}

local l_wuqian_dist = fk.CreateDistanceSkill{
  name = "#l_wuqian_dist",
  correct_func = function(self, from, to)
    if from:hasSkill("l_wuqian") then
      return -1
    end
  end,
}

local l__lvbu = General(extension,"l__lvbu","qun",5)
l__lvbu:addSkill(l_wushuang)
l__lvbu:addSkill(l_wumou)
l__lvbu:addSkill(l_wuqian)
l_wushuang:addRelatedSkill(l_wushuang_tarmod)
l_wumou:addRelatedSkill(l_wumou_duel_slash)
l_wumou:addRelatedSkill(l_wuqian_dist)
Fk:loadTranslationTable{
    ["l__lvbu"] = "吕布",
    ["l_wushuang"] = "无双",
    [":l_wushuang"] = "锁定技，当你使用“杀” 或“决斗”指定目标后，至多指定两名其他角色为目标;你使用的“ 杀”需打出4-X张“闪”才能抵消;与你进行“决斗”的角色需连续打出4-X张“杀”( X为此牌指定的目标数)。",

    ["l_wumou"] = "无谋",
    [":l_wumou"] = "锁定技，你的锦囊牌于回合内视为“决斗”；回合外视为“杀”。",
    ["#l_wumou_duel_slash"] = "无谋",
    ["#l_wushuang_invoke"] = "请选择至多其他两名角色为决斗目标",

    ["l_wuqian"] = "无前",
    [":l_wuqian"] = "你计算与其他角色的距离-1;当你成为其他角色使用‘杀”的目标时，你可以对其使用一张“杀”。",
    ["#l_wuqian_dist"] = "无前",
    ["l_wuqian_slash"] = "是否发动无前对 %dest 出杀"
}

--吕布（修罗神话）
local l_shenwu = fk.CreateTriggerSkill{
  name = "l_shenwu",
  anim_type = "control",
  frequency = Skill.Compulsory,
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self.name)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id)
      if card.name == "shfthj" or card.name == "shsfzjg" or card.name == "shttk" then
        if room:getCardArea(id) == Card.Void then
          room:moveCards({
            ids = {id},
            fromArea = Card.Void,
            to = player.id,
            toArea = Card.PlayerEquip,
            moveReason = fk.ReasonJustMove,
            proposer = player.id,
            skillName = self.name,
          })
          if player:getEquipment(Card.SubtypeWeapon) and player:getEquipment(Card.SubtypeTreasure) and player:getEquipment(Card.SubtypeArmor) then
              break
          end
        end
      end
    end 
  end
}

local l_shenzhan = fk.CreateTriggerSkill{
  name = "l_shenzhan",
--   anim_type = "control",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart,fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      return player:hasSkill(self.name) and target == player and player.phase == Player.Start
    else
      return player:hasSkill(self.name) and target == player 
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, self.name, "drawcard")
    if event == fk.EventPhaseStart then
        room:drawCards(player,#room.alive_players < 4 and 2 or 3,self.name)
    else
      room:drawCards(player,1,self.name)
    end
  end,
}

local l_shenzhan_slashmod = fk.CreateTargetModSkill{
  name = "#l_shenzhan_slashmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and player:getMark("form_phase") > 0 then
      return player:getMark("form_phase") + 1
    end
  end,
}

local l__xiuluolvbu = General(extension,"l__xiuluolvbu","qun",20)
l__xiuluolvbu:addSkill(l_shenwu)
l__xiuluolvbu:addSkill(l_shenzhan)
l__xiuluolvbu:addSkill("l_wuqian")
l_shenzhan:addRelatedSkill(l_shenzhan_slashmod)
-- l__yuanshu:addSkill(l_rongzhu)
Fk:loadTranslationTable{
    ["l__xiuluolvbu"] = "修罗神话吕布",
    ["l_shenwu"] = "神武",
    [":l_shenwu"] = "锁定技，游戏开始把你所属得装备（神话方天画戟）（神话吞天铠）（神话束发紫金冠）  转变形态：（当体力小于9吕布转变第3形态。立刻结束当前角色回合，吕布获得一个额外得回合）",

    ["l_shenzhan"] = "神战",
    [":l_shenzhan"] = "锁定技，准备阶段开始多摸(存活角色数<4为2,否则为3)张牌，出牌阶段你可以多使用X张【杀】;一名角色回合结束时，你摸1张牌（X为形态数，初始为1）",

    ["l_shenzhi"] = "神智",
    [":l_shenzhi"] = "锁定技，濒死状态下你弃掉所有桃回复自身等量体力，若满体力，每弃置1张桃摸两张牌，你使用锦囊不可被【无懈可击】响应",
}

--吕布（虎牢关）
local l_jingjia = fk.CreateTriggerSkill{
  name = "l_jingjia",
  anim_type = "control",
  frequency = Skill.Compulsory,
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self.name)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(Fk:getAllCardIds()) do
        local card = Fk:getCardById(id)
        if card.name == "llsmd" or card.name == "wxfthj" then
            if room:getCardArea(id) == Card.Void then
                room:moveCards({
                    ids = {id},
                    fromArea = Card.Void,
                    to = player.id,
                    toArea = Card.PlayerEquip,
                    moveReason = fk.ReasonJustMove,
                    proposer = player.id,
                    skillName = self.name,
                })
                if player:getEquipment(Card.SubtypeWeapon) and player:getEquipment(Card.SubtypeArmor) then
                    break
                end
            end
        end
    end 
  end
}

local l_aozhan = fk.CreateTriggerSkill{
  name = "l_aozhan",
  anim_type = "control",
  frequency = Skill.Compulsory,
  events = {fk.DrawNCards,fk.TargetSpecified,fk.EventPhaseStart,fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    if event == fk.DrawNCards then
        return player:hasSkill(self.name) and target == player
    elseif event == fk.TargetSpecified then
        return target == player and player:hasSkill(self.name) and data.from == player.id and player:getMark("l_aozhan_slash_mode") == 0 and not player:getEquipment(Card.SubtypeWeapon) and data.card and data.card.trueName == "slash"
    elseif event == fk.EventPhaseStart then
        -- body
        if player:hasSkill(self.name) and target == player and player.phase == Player.Play then
            if player:getEquipment(Card.SubtypeWeapon) then
                return true
            else
                player.room:setPlayerMark(player,"l_aozhan_slash_mode",0)
                return false
            end
        end
    else
        return player:hasSkill(self.name) and target.phase == Player.Finish and #player.player_cards[Player.Hand] <= player.maxHp and player ~= target
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.DrawNCards then
        data.n = data.n + #room:getOtherPlayers(player)
    elseif event == fk.TargetSpecified then
        data.additionalDamage = (data.additionalDamage or 0) + 1
    elseif event == fk.EventPhaseStart then
        room:setPlayerMark(player,"l_aozhan_slash_mode",#room:getOtherPlayers(player))
    else
        room:drawCards(player,#room.alive_players > 4 and 3 or 2,self.name)
    end
  end,
}


local l_aozhan_tarmod = fk.CreateTargetModSkill{
  name = "#l_aozhan_tarmod",
  extra_target_func = function(self, player, skill)
    if skill.trueName == "slash_skill" and player:hasSkill("l_aozhan") and player:getMark("l_aozhan_slash_mode") == 0 and not player:getEquipment(Card.SubtypeWeapon) then
      return 2
    end
  end,
}

local l_aozhan_slashmod = fk.CreateTargetModSkill{
    name = "#l_aozhan_slashmod",
    residue_func = function(self, player, skill, scope)
        local room = player.room
        if skill.trueName == "slash_skill" and player:hasSkill("l_aozhan") and player:getMark("l_aozhan_slash_mode") > 0 then
            
            -- local op = room:getOtherPlayers(player)
            return player:getMark("l_aozhan_slash_mode")
        end
    end,
}

local l__hulaolvbu = General(extension,"l__hulaolvbu","qun",9)
l__hulaolvbu:addSkill(l_jingjia)
l__hulaolvbu:addSkill(l_aozhan)
l_aozhan:addRelatedSkill(l_aozhan_tarmod)
l_aozhan:addRelatedSkill(l_aozhan_slashmod)
-- l__yuanshu:addSkill(l_rongzhu)
Fk:loadTranslationTable{
    ["l__hulaolvbu"] = "虎牢关吕布",
    ["l_jingjia"] = "精甲",
    [":l_jingjia"] = "锁定技，游戏开始把你所属得装备（无双方天画戟）（玲珑狮带）置于你的装备区",

    ["l_aozhan"] = "鏖战",
    [":l_aozhan"] = "锁定技，摸牌阶段多摸X张牌，出牌阶段开始时若你装备区内有武器牌，你可以多使用X张【杀】；否则你使用【杀】指向目标+2且伤害+1;每名其他角色回合结束时，若你的手牌小于等于体力值上限则你摸两张牌(若存活角色数大于4改为摸3张)（X为总存活角色数）",

}

--袁术
local l_yongsi = fk.CreateTriggerSkill{
  name = "l_yongsi",
--   anim_type = "control",
  frequency = Skill.Compulsory,
  events = {fk.BeforeCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self.name) then
        for _, move in ipairs(data) do
            if fk.ReasonDraw == move.moveReason and move.to and move.to == player.id and move.toArea and move.toArea == Card.PlayerHand then
                if not move.skillName then
                    return true
                end
                if move.skillName and move.skillName ~= self.name then
                    return true
                end
            end
        end
    end
  end,
  on_use = function(self, event, target, player, data)
    local ids = {}
    local room = player.room
    for _, move in ipairs(data) do
        if fk.ReasonDraw == move.moveReason and move.to and move.to == player.id and move.toArea and move.toArea == Card.PlayerHand then
            local move_info = {}
            for _, info in ipairs(move.moveInfo) do
                if info.fromArea == Card.DrawPile then
                    table.insert(ids, info.cardId)
                end
            end
            if #ids > 0 then
                move.moveInfo = move_info
                local kingdomlist = {}
                for index, p in ipairs(room:getAlivePlayers()) do
                    table.insertIfNeed(kingdomlist,p.kingdom)
                end
                room:drawCards(player,#kingdomlist,self.name)
                if #kingdomlist-1 > 0 then
                    room:askForDiscard(player,#kingdomlist-1,#kingdomlist-1,true,self.name,false)
                end
            end
        end
    end
    if #ids > 0 then
      player.room:sendLog{
        type = "#drawDismantle",
        card = ids,
        arg = self.name,
      }
    end
  end,
}

local l_kuixi = fk.CreateTriggerSkill{
  name = "l_kuixi",
  anim_type = "control",
  events = {fk.RoundStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self.name)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if not player:getEquipment(Card.SubtypeTreasure) or Fk:getCardById(player:getEquipment(Card.SubtypeTreasure)).name ~= "yx_yvxi" then
      return room:askForSkillInvoke(player, self.name, nil, "#l_kuixi-invoke")
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id, true)
      if card.name == "yx_yvxi" then
        player:throwAllCards("h")
        local area = room:getCardArea(card.id)
        if area == Player.Hand or area == Player.Equip or area == Player.Special then
          room:obtainCard(player.id,id,true,fk.ReasonJustMove)
          LU:putEquipHandle(player,Card.SubtypeTreasure,id,player.id,self.name)
        else
          LU:putEquipHandle(player,Card.SubtypeTreasure,id,player.id,self.name)
        end
        break
      end
    end
  end,
  refresh_events = {fk.BeforeCardsMove},
    can_refresh = function (self, event, target, player, data)
        if player:hasSkill(self.name) then
            if player:getEquipment(Card.SubtypeTreasure) and Fk:getCardById(player:getEquipment(Card.SubtypeTreasure)).name == "yx_yvxi" then
                for _, move in ipairs(data) do
                    -- p(move)
                    
                    if fk.ReasonDiscard == move.moveReason and move.from and move.proposer and move.from == player.id and move.proposer == move.from and move.toArea and move.toArea == Card.DiscardPile then
                        if not move.skillName then
                            return true
                        end
                        if move.skillName and move.skillName ~= "#yx_yvxi_skill" then
                            return true
                        end
                    end
                end
            end
            
        end
    end,
    on_refresh = function (self, event, target, player, data)
        local ids = {}
        local room = player.room
        for _, move in ipairs(data) do
            if fk.ReasonDiscard == move.moveReason and move.from and move.proposer and move.from == player.id and move.proposer == move.from and move.toArea and move.toArea == Card.DiscardPile then
                local move_info = {}
                for _, info in ipairs(move.moveInfo) do
                    table.insert(ids, info.cardId)
                end
                if #ids > 0 then
                    move.moveInfo = move_info
                end
            end
        end
        if #ids > 0 then
        player.room:sendLog{
            type = "#cancelDismantle",
            card = ids,
            arg = self.name,
        }
        end
    end
}

local l__yuanshu = General(extension,"l__yuanshu","qun",4)
l__yuanshu:addSkill(l_yongsi)
-- l__yuanshu:addSkill(shenxing)
-- l_tiangong:addRelatedSkill(l_tiangong_prohibit_armor)
l__yuanshu:addSkill(l_kuixi)
-- l__yuanshu:addSkill(l_rongzhu)
Fk:loadTranslationTable{
    ["l__yuanshu"] = "袁术",
    ["l_yongsi"] = "庸嗣",
    [":l_yongsi"] = "锁定技，当你摸牌时，改为摸X张牌，然后弃置×-1张牌（X为存活势力数）",

    ["l_kuixi"] = "窥玺",
    [":l_kuixi"] = "每轮开始时，若你没有装备“玉玺”，你可以弃置所有手牌将“玉玺”置入你的装备区（无论在哪）：当你装备“玉玺”时，你不能执行你对自己牌的弃置操作：当“玉玺”离开你的装备区后，你弃置所有牌",

    ["#l_kuixi-invoke"] = "窥玺：是否获得玉玺",
    ["#drawDismantle"] = "由于“%arg”的效果，%card 的摸牌被取消",
}

--孙尚香
local l_qingrong = fk.CreateTriggerSkill{
  name = "l_qingrong",
--   anim_type = "control",
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and player.phase == Player.Play and data.card.type == Card.TypeEquip
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local eqnum = #player.player_cards[Player.Equip]
    if eqnum < 3 then
        local equiptype = data.card.sub_type -2
        local equiptotal = {"weapon","armor", "defensive_ride","offensive_ride","treasure"}
        
        if equiptotal[equiptype] then
            table.remove(equiptotal,equiptype)
            -- local fn
            local function filtreasure(v)
                if equiptotal[v] == "treasure" then
                    print(equiptotal[v])
                    return filtreasure(math.random(1,#equiptotal))
                else
                    return equiptotal[v]
                end
            end
            local v = filtreasure(math.random(1,#equiptotal))
            local exptern = ".|.|.|.|.|".. v
            -- print(exptern)
            local cards = room:getCardsFromPileByRule(exptern, 1, "drawPile")
            if #cards > 0 then
                player.room:obtainCard(player, cards[1], true, fk.ReasonJustMove)
            end
        end
    else
        if #player.player_cards[Player.Hand] > 0 then
            room:throwCard(table.random(player.player_cards[Player.Hand], 1), self.name, player, player)
        end
    end
    if data.card.sub_type == Card.SubtypeWeapon then
        local othertas = {}
        for key, p in pairs(room:getOtherPlayers(player)) do
            if player:inMyAttackRange(p) then
                table.insert(othertas,p.id)
            end
        end
        local tars = room:askForChoosePlayers(player,othertas,1,1,"#l_qingrong_slash",self.name,true)  
        room:useVirtualCard("slash", nil, player,room:getPlayerById(tars[1]), self.name,true)
    elseif data.card.sub_type == Card.SubtypeArmor then
        room:drawCards(player, 1, self.name)
    elseif data.card.sub_type == Card.SubtypeDefensiveRide then
        room:addPlayerMark(player,"@l_qingrong_handmax",1)
    elseif data.card.sub_type == Card.SubtypeOffensiveRide then
        room:setPlayerMark(player,"@@l_qingrong_disresponse",1)
    end
  end,
  refresh_events = {fk.EventPhaseEnd},
    can_refresh = function (self, event, target, player, data)
        return player:hasSkill(self.name) and player == target and player.phase == Player.Finish
    end,
    on_refresh = function (self, event, target, player, data)
        local room = player.room
        if player:getMark("@l_qingrong_handmax") > 0 then
            room:setPlayerMark(player,"@l_qingrong_handmax",0)
        end
        if player:getMark("@@l_qingrong_disresponse") > 0 then
            room:setPlayerMark(player,"@@l_qingrong_disresponse",0)
        end
    end
}

local l_qingrong_handmax = fk.CreateMaxCardsSkill{
  name = "#l_qingrong_handmax",
  correct_func = function (self, player)
    if player:hasSkill(self.name) and player:getMark("@l_qingrong_handmax") > 0 then
      return player:getMark("@l_qingrong_handmax")
    end
  end,
}

local l_qingrong_disresponse = fk.CreateTriggerSkill{
    name = "#l_qingrong_disresponse",
    -- anim_type = "",
    frequency = Skill.Compulsory,
    events = {fk.TargetSpecified},
    can_trigger = function (self, event, target, player, data)
        return target == player and player:hasSkill(self.name) and data.card and data.card.trueName == "slash" and player:getMark("@@l_qingrong_disresponse") == 1
    end,
    on_use = function(self, event, target, player, data)
        local room = player.room
        -- 杀不可响应
        data.disresponsive = true
     end,
    refresh_events = {fk.CardUseFinished},
    can_refresh = function (self, event, target, player, data)
        return player:hasSkill(self.name) and player == target and data.card and data.card.trueName == "slash" and player:getMark("@@l_qingrong_disresponse") == 1
    end,
    on_refresh = function (self, event, target, player, data)
        local room = player.room
        room:setPlayerMark(player,"@@l_qingrong_disresponse",0)
    end
}

local l_yuanhu = fk.CreateActiveSkill{
    name = "l_yuanhu",
    anim_type = "support",
    frequency = Skill.Limited,
    target_num = 1,
    card_num = 0,
    can_use = function(self,player)
        return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
    end,
    card_filter = function(self, to_select, selected)
        return false
    end,
    target_filter = function(self, to_select, selected)
        return #selected == 0 and to_select ~= Self.id
    end,
    on_use = function(self, room, effect)
        local player = room:getPlayerById(effect.from)
        local target = room:getPlayerById(effect.tos[1])

        --移动的装备区装备卡
        local eqcards = player.player_cards[Player.Equip]
        local eqnum = #eqcards
        local clonequids = table.clone(eqcards)
        
        room:moveCards({
            from = player.id,
            ids = eqcards,
            toArea = Card.Processing,
            moveReason = fk.ReasonJustMove,
            proposer = player.id,
            skillName = self.name,
        })
        
        for i, peqcid in pairs(clonequids) do
            
            local card = Fk:getCardById(peqcid)
            local teqcid = target:getEquipment(card.sub_type)
            local move3 = {
                ids = {peqcid},
                fromArea = Card.Processing,
                to = target.id,
                toArea = Card.PlayerEquip,
                moveReason = fk.ReasonJustMove,
                proposer = player.id,
                skillName = self.name,
            }
            if teqcid ~= nil then
                local move2 = {
                    ids = {teqcid},
                    from = target.id,
                    toArea = Card.DiscardPile,
                    moveReason = fk.ReasonJustMove,
                }
                room:moveCards(move2, move3)
            else
                room:moveCards(move3)
            end
        end

        room:drawCards(player, eqnum, self.name)
        
        --交换手牌
        if #player.player_cards[Player.Hand] > #target.player_cards[Player.Hand] then
            local move1 = {
                from = player.id,
                ids = player.player_cards[Player.Hand],
                to = target.id,
                toArea = Card.PlayerHand,
                moveReason = fk.ReasonExchange,
                proposer = player.id,
                skillName = self.name,
            }
            local move2 = {
                from = target.id,
                ids = target.player_cards[Player.Hand],
                to = player.id,
                toArea = Card.PlayerHand,
                moveReason = fk.ReasonExchange,
                proposer = player.id,
                skillName = self.name,
            }
            room:moveCards(move1, move2)
        end

        --恢复体力与你一致
        if player.hp > target.hp then
            room:recover({
                who = target,
                num = player.hp - target.hp,
                recoverBy = player,
                skillName = self.name
            })
        end
    end,
}

local l__sunshangxiang = General(extension, "l__sunshangxiang", "wu", 4,4,2)
l__sunshangxiang:addSkill(l_qingrong)
l_qingrong:addRelatedSkill(l_qingrong_handmax)
l_qingrong:addRelatedSkill(l_qingrong_disresponse)
l__sunshangxiang:addSkill(l_yuanhu)
Fk:loadTranslationTable{
  ["l__sunshangxiang"] = "孙尚香",
  ["l_qingrong"] = "轻戎",
  [":l_qingrong"] = "出牌阶段，每当你使用装备牌，若装备区装备数量小于3，你从牌堆随机获得1张与使用装备类型不同的装备牌，否则你随机丢弃一张手牌；每当你使用装备牌根据类型获得以下效果：<br/>1.武器，视为对攻击范围内其他角色使用不计入次数【杀】<br/>2.防具，摸1张牌<br/>3.防御马，手牌上限+1<br/>4.进攻马，你使用下一张【杀】不可被响应",
  ["l_yuanhu"] = "缘护",
  [":l_yuanhu"] = "限定技，你可以把你装备区的所有装备置于一名其他角色装备区中并摸置于其装备数量的牌；若你的手牌比其多，交换你与其手牌，若你的体力比其多，其恢复的体力等同于你",
  ["@l_qingrong_handmax"] = "手牌上限+",
  ["@@l_qingrong_disresponse"] = "杀不可响应",
  ["#l_qingrong_disresponse"] = "轻戎",
  ["#l_qingrong_slash"] = "轻戎：选择攻击范围内一名其他角色视为使用【杀】"
}

--张辽
local l_tuxi = fk.CreateTriggerSkill{
  name = "l_tuxi",
  anim_type = "control",
  events = {fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and data.n > 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(room:getOtherPlayers(player), function (p) return p.id end)
    local tos = room:askForChoosePlayers(player, targets, 1, data.n, "#l_tuxi-choose:::"..data.n, self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:useVirtualCard("slash", nil, player, table.map(self.cost_data,function (id)
        return room:getPlayerById(id)
    end), self.name)
    data.n = data.n - #self.cost_data
  end,
}

local l_liezhen = fk.CreateTriggerSkill{
  name = "l_liezhen",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    
    return player:hasSkill(self.name) and data.from == player.id and data.card and data.card.trueName == "slash"
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local tar = room:getPlayerById(data.to)
    if not tar:isNude() and player.room:askForSkillInvoke(player, self.name, data) then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tar = room:getPlayerById(data.to)
    local obcardnum = (#tar.player_cards[Player.Hand] + #tar.player_cards[Player.Equip])/2
    if obcardnum == 0 then return end
    if obcardnum > 0 and obcardnum < 1 then
        obcardnum = 1
    end
    obcardnum = math.floor(obcardnum)
    -- local cards = room:askForCardsChosen(player,tar,obcardnum,obcardnum,"he",self.name)
    local cards = tar:getCardIds{Player.Hand,Player.Equip}
    if #cards == 0 then return end
    cards = table.random(cards,obcardnum)
    local dummy = Fk:cloneCard("dilu")
    dummy:addSubcards(cards)
    room:obtainCard(player.id,dummy,false,fk.ReasonGive)
    -- self.cost_data = self.cost_data or {}
    data.card.l_liezhenmes = data.card.l_liezhenmes or {}
    table.insertIfNeed(data.card.l_liezhenmes,{data.to,#cards})
    room:setCardMark(data.card,"l_liezhen_slash",1)
  end,
  refresh_events = {fk.CardUseFinished},
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(self.name) and target == player and data.card and data.card:getMark("l_liezhen_slash")==1 and data.card.trueName == "slash" and data.card.l_liezhenmes and #data.card.l_liezhenmes > 0
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if not data.card.l_liezhenmes or #data.card.l_liezhenmes == 0 then return end
    if data.damageDealt then
      local damageidlist = {}
      for id, v in pairs(data.damageDealt) do
          table.insert(damageidlist,id)
      end
      for i = 1, #damageidlist do
        for j = 1, #data.card.l_liezhenmes do
            local leizhenmes = data.card.l_liezhenmes[j]
            if leizhenmes and damageidlist[i] and leizhenmes[1] == damageidlist[i] then
                table.remove(data.card.l_liezhenmes,j)
            end
        end
      end
      for k, pp in pairs(data.card.l_liezhenmes) do
        local tar = room:getPlayerById(pp[1])
        if tar then
          local givenum = pp[2]
          local cards = room:askForCard(player,givenum,givenum,true,self.name,false,"","l_liezhen_give::"..tar.id)
          local dummy = Fk:cloneCard("dilu")
          dummy:addSubcards(cards)
          room:obtainCard(tar.id,dummy,false,fk.ReasonGive)
        end
      end
    else
      for j, pp in pairs(data.card.l_liezhenmes) do
        if not pp[1] or not pp[2] then return end
        local tar = room:getPlayerById(pp[1])
        if not tar then return end
        local givenum = pp[2]
        local cards = room:askForCard(player,givenum,givenum,true,self.name,false,"","l_liezhen_give::"..tar.id)
        local dummy = Fk:cloneCard("dilu")
        dummy:addSubcards(cards)
        room:obtainCard(tar.id,dummy,false,fk.ReasonGive)
      end
      if player:usedSkillTimes("l_tuxi", Player.HistoryTurn) == 1 then
        player:skip(Player.Play)
      end
    end
    data.card.l_liezhenmes = nil
    room:setCardMark(data.card,"l_liezhen_slash",0)
  end
}

local l__zhangliao = General(extension, "l__zhangliao", "wei", 4)
l__zhangliao:addSkill(l_tuxi)
l__zhangliao:addSkill(l_liezhen)
Fk:loadTranslationTable{
  ["l__zhangliao"] = "张辽",
  ["l_tuxi"] = "突袭",
  [":l_tuxi"] = "摸牌阶段，你可以少摸任意张牌并视为对等量的其他角色使用一张无距离不计入次数“杀”，此“杀”结算后，若该牌未造成伤害，则跳过出牌阶段。",
  ["l_liezhen"] = "裂阵",
  [":l_liezhen"] = "当你使用“杀”指定目标后，获得其一半牌(向下取整最少为1)，若此“杀”未造成伤害，则交给其等量牌。",
  
  ["#l_tuxi-choose"] = "你可以少%arg张牌并视为对等量的其他角色使用一张“杀”",
  ["l_liezhen_give"] = "裂阵：交给 %dest 等量的牌",
}

--关羽
local l_zhenfan = fk.CreateActiveSkill{
  name = "l_zhenfan",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_use = function(self,player)
    return player:hasSkill(self.name) and player:usedSkillTimes(self.name) == 0 and not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected)
        local is_difsuit = function ()
            local card = Fk:getCardById(to_select)
            -- print(card_area)
            if Fk:currentRoom():getCardArea(to_select) ~= Player.Equip then
                for key, sel_card_id in pairs(selected) do
                    if Fk:getCardById(sel_card_id).suit == card.suit then
                        return false
                    end
                end
                return true
            end
        end
        local selectNum = function ()
            local mark = Self:getMark("l_zhenfan_showcards_mark")
            if mark == 0 then
                return 2
            else
                return 3
            end
        end
        return is_difsuit() and #selected < selectNum()
  end,
  min_card_num = 1,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    player:showCards(effect.cards)
    if #effect.cards >= 1 then
        room:setPlayerMark(player,"l_zhenfan_show_mark",1)
    end
    if #effect.cards >= 2 then
        room:handleAddLoseSkills(player, "wusheng", nil, true, false)
        room:setPlayerMark(player,"l_zhenfan_show_mark",2)
    end
    if #effect.cards >= 3 then
        room:drawCards(player, 3, self.name)
        
        if not player:isNude() then
            room:askForDiscard(player,2,2,true,self.name,false)
        end
        room:setPlayerMark(player,"l_zhenfan_show_mark",3)
    end
    
    local card_suits_table = {
          spade = "♠",
          club = "♣",
          heart = "♥",
          diamond = "♦",
    }
    for key, cid in pairs(effect.cards) do
        local card = Fk:getCardById(cid)
        local mark = player:getMark("@l_zhenfan_record_mark")
        if mark == 0 then
            room:setPlayerMark(player,"@l_zhenfan_record_mark",card_suits_table[card:getSuitString()])
        elseif type(mark) == "string" then
            -- body
            room:setPlayerMark(player,"@l_zhenfan_record_mark",mark + card_suits_table[card:getSuitString()])
        end
        
    end
    --选择花色数目玩家
    local other_tars = {}
    for key, tar in pairs(room:getOtherPlayers(player)) do
        table.insert(other_tars,tar.id)
    end
    local select_tars = room:askForChoosePlayers(player,other_tars,0,#effect.cards,"#l_zhenfan_select",self.name,true)
    -- room.askForChoosePlayers()
    if #select_tars == 0 then
        return
    end
    local chc = {"l_zhenfan_givecards","Cancel"}
    for key, sel_tar in pairs(select_tars) do
        local sel_target = room:getPlayerById(sel_tar)
        local chs = room:askForChoice(sel_target,chc,self.name)
        if chs == "Cancel" then
            room:setPlayerMark(sel_target,"@l_zhenfan_nogive_mark",#effect.cards)
        else
            --展示花色数大于给的花色数目标获得负面效果
            local cards = {}
            local cards_suit = {}
            local filter_suit = function (area)
                for key1, tar_cardid in pairs(sel_target.player_cards[area]) do
                    for key2, sel_cardid in pairs(effect.cards) do
                        local tar_card = Fk:getCardById(tar_cardid)
                        local sel_card = Fk:getCardById(sel_cardid)
                        if tar_card.suit == sel_card.suit then
                            table.insert(cards,tar_card.id)
                            table.insertIfNeed(cards_suit,tar_card.suit)
                        end
                    end 
                end
            end
            filter_suit(Player.Hand)
            filter_suit(Player.Equip)
            local dummy = Fk:cloneCard("dilu")
            dummy:addSubcards(cards)
            room:obtainCard(player,dummy,false,fk.ReasonGive)
            
            room:setPlayerMark(sel_target,"@l_zhenfan_nogive_mark",#effect.cards - #cards_suit)
        end
    end
  end,
}


--目标给关羽展示花色牌相差2，关羽对目标伤害+1，相差3，目标也成为杀对象
local l_zhenfan_damage_trig = fk.CreateTriggerSkill{
    name = "#l_zhenfan_damage_trig",
    events = {fk.DamageCaused},
    can_trigger = function(self, event, target, player, data)
        if target == player and player:hasSkill(self.name) then
            if player.phase == Player.Play then
                local to = data.to
                local mark = to:getMark("@l_zhenfan_nogive_mark")
                if mark > 1 and to:getMark("l_zhenfan_damage_turn") == 0 then
                    return true
                end
            end
        end
    end,
    on_cost = function(self, event, target, player, data)
        return true
    end,
    on_use = function(self, event, target, player, data)
        local room = player.room
        if event == fk.DamageCaused then
            data.damage = data.damage + 1
            local to = data.to
            room:setPlayerMark(to,"l_zhenfan_damage_turn",1)
        end
    end,
    refresh_events = {fk.TargetSpecifying},
    can_refresh = function (self, event, target, player, data)
        if target == player and player:hasSkill(self.name) and #AimGroup:getAllTargets(data.tos) == 1 and data.from == player.id and data.card and data.card.trueName == "slash"then
            local availableTargets = {}
            for _, p in ipairs(player.room:getOtherPlayers(player)) do
                if p:getMark("@l_zhenfan_nogive_mark") > 2 and not table.contains(TargetGroup:getRealTargets(data.tos), p.id) then
                    table.insert(availableTargets, p.id)
                end
            end
            if #availableTargets > 0 then
                self.cost_data = availableTargets
                return true
            else
                self.cost_data = nil
                return false
            end
        end
        
    end,
    on_refresh = function (self, event, target, player, data)
        local room = player.room
        
        if self.cost_data then
            room:doIndicate(player.id, self.cost_data)
            table.forEach(self.cost_data, function(pid)
                -- AimGroup:addTargets(room, data, pid)
                TargetGroup:pushTargets(data.targetGroup, pid)
            end)
            self.cost_data = nil
        end
    end
}

--目标给关羽展示花色牌相差1，关羽与目标距离为1
local l_zhenfan_dis = fk.CreateDistanceSkill{
  name = "#l_zhenfan_dis",
  correct_func = function(self, from, to)
    if from:hasSkill(self.name) then
      if to:getMark("@l_zhenfan_nogive_mark") > 0 then
        from:setFixedDistance(to, 1)
      else
        from:removeFixedDistance(to)
      end
    end
    return 0
  end,
}

--结束阶段关羽武圣，杀+1效果结束
local l_zhenfan_end_trig = fk.CreateTriggerSkill{
    name = "#l_zhenfan_end_trig",
    events = {fk.EventPhaseStart,fk.EventPhaseEnd},
    can_trigger = function(self, event, target, player, data)
        if event == fk.EventPhaseStart then
            return target == player and player:hasSkill(self.name) and player.phase == Player.Start and type(player:getMark("@l_zhenfan_record_mark")) == "string" and string.len(player:getMark("@l_zhenfan_record_mark")) > 0
        else
            return target == player and player:hasSkill(self.name) and player.phase == Player.Finish and player:getMark("l_zhenfan_show_mark") > 0
        end
        
    end,
    on_cost = function (self, event, target, player, data)
        return true
    end,
    on_use = function(self, event, target, player, data)
        local room = player.room
        if event == fk.EventPhaseStart then
            room:setPlayerMark(player,"@l_zhenfan_record_mark",0)
            room:setPlayerMark(player,"l_qingao_mark",0)
            room:setPlayerMark(player,"l_zhenfan_showcards_mark",1)
        else
            --移除武圣技能
            local zhenfan_mark = player:getMark("l_zhenfan_show_mark")
            if zhenfan_mark >= 2 then
                
                room:handleAddLoseSkills(player,"-wusheng", nil, true, false)
            end
            room:setPlayerMark(player,"l_zhenfan_show_mark",0)
            --移除目标标记
            for key, op in pairs(room:getAlivePlayers()) do
                if op:getMark("@l_zhenfan_nogive_mark") > 0 then
                    room:setPlayerMark(op,"@l_zhenfan_nogive_mark",0)
                end
                if op:getMark("l_zhenfan_damage_turn") > 0 then
                    room:setPlayerMark(op,"l_zhenfan_damage_turn",0)
                end
            end 
        end
    end,
}

local l_zhenfan_targetmod = fk.CreateTargetModSkill{
    name = "#l_zhenfan_targetmod",
    residue_func = function(self, player, skill, scope)
        if player:getMark("l_zhenfan_show_mark") > 0 and skill.trueName == "slash_skill" and scope == Player.HistoryPhase then
            return 1
        end
    end,
}

local l_qingao = fk.CreateTriggerSkill{
  name = "l_qingao",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self.name) and player.phase == Player.NotActive then
      for _, move in ipairs(data) do
        if move.from == player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                local mark = player:getMark("@l_zhenfan_record_mark")
                if type(mark) == "string" then
                    local card_suits_table = {
                        spade = "♠",
                        club = "♣",
                        heart = "♥",
                        diamond = "♦",
                    }
                    local totsuit = #mark
                    local card = Fk:getCardById(info.cardId)
                    local suit = card_suits_table[card:getSuitString()]
                    
                    local index = string.find(mark,suit)
                    local room = player.room
                    if index then
                        local newmark = string.gsub(mark,suit,"")
                        room:setPlayerMark(player,"@l_zhenfan_record_mark",newmark)
                        room:addPlayerMark(player,"l_qingao_mark",1)
                        return true
                    end
                end
            end
          end
        end
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
        return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    
    local qingao_mark = player:getMark("l_qingao_mark")
    local zhenfan_record_mark = player:getMark("@l_zhenfan_record_mark")
    if qingao_mark == 1 then
        if not player:isNude() then
            room:askForDiscard(player,1,1,true,self.name,false)
        end
    elseif qingao_mark == 2 then
        room:setPlayerMark(player,"@l_qingao_damaged_add",1)
    elseif qingao_mark == 3 then
        player:turnOver()
    end
    if type(zhenfan_record_mark) == "string" and #zhenfan_record_mark == 0 then
        room:setPlayerMark(player,"@l_zhenfan_record_mark",0)
        room:setPlayerMark(player,"l_qingao_mark",0)
        room:setPlayerMark(player,"l_zhenfan_showcards_mark",0)
    end
  end,
  refresh_events = {fk.TargetSpecified,fk.EventPhaseEnd},
  can_refresh = function (self, event, target, player, data)
    if event == fk.TargetSpecified then
        return target ~= player and player.phase == Player.NotActive and player:hasSkill(self.name) and player:getMark("@l_qingao_damaged_add") > 0
    else
        return target ~= player and player.phase == Player.NotActive and player:hasSkill(self.name) and target.phase == Player.Finish and player:getMark("@l_qingao_damaged_add") > 0
    end
    
  end,
  on_refresh = function (self, event, target, player, data)
     local room = player.room
     if event == fk.TargetSpecified then
        data.additionalDamage = (data.additionalDamage or 0) + 1
    else
        room:removePlayerMark(player,"@l_qingao_damaged_add",1)
    end
  end
}

local l__guanyu = General(extension, "l__guanyu", "shu", 4)
l_zhenfan:addRelatedSkill(l_zhenfan_damage_trig)
l_zhenfan:addRelatedSkill(l_zhenfan_dis)
l_zhenfan:addRelatedSkill(l_zhenfan_end_trig)
l_zhenfan:addRelatedSkill(l_zhenfan_targetmod)
l__guanyu:addSkill(l_zhenfan)
l__guanyu:addSkill(l_qingao)
Fk:loadTranslationTable{
  ["l__guanyu"] = "关羽",
  ["l_zhenfan"] = "震樊",
  [":l_zhenfan"] = "出牌阶段限一次，你可以展示最多两种花色不同的手牌并选择对应花色数量的目标令其选择是否交给你展示花色的所有牌，若目标交给你牌中的花色每少于X种你获得以下效果：<br/>1.你与其距离视为1，<br/>2.你对其造成伤害+1(限一次)，<br/>3.其也成为你杀的目标;<br/>每当以此法展示花色时，你获得以下X种效果:<br/>1.出牌阶段杀次数+1，<br/>2.获得【武圣】直到回合结束，<br/>3.摸三张牌然后弃两张。",
  ["l_qingao"] = "傲势",
  [":l_qingao"] = "每当发动【震樊】时，展示的花色被记录在武将面板上;当你于回合外失去牌后，若牌的花色与记录的花色有相同，移除该花色记录并根据被移除数量获得以下第X种效果:<br/>1.弃置一张牌，<br/>2.当前回合你受到伤害+1，<br/>3.你被翻面;<br/>准备阶段开始时若武将面板上有记录花色，则【震樊】展示手牌最多为3并清除所有花色记录。(X为展示花色数)",
  ["#l_zhenfan_end_trig"] = "震樊",
  ["#l_zhenfan_damage_trig"] = "震樊",
  ["@l_zhenfan_nogive_mark"] = "震",
  ["l_zhenfan_givecards"] = "交给展示花色的所有牌",
  ["#l_zhenfan_select"] = "选择对象",
  ["@l_zhenfan_record_mark"] = "震樊:",
  ["#l_zhenfan_discard"] = "弃置 %dest 张牌",
  ["@l_qingao_damaged_add"] = "伤害+"
}

--白起
local l_wuan = fk.CreateTriggerSkill{
  name = "l_wuan",
  events = {fk.EventPhaseChanging,fk.TargetConfirming},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self.name) then
        if event ==fk.TargetConfirming then
            return player.phase == Player.NotActive and data.to == player.id and player:getMark("@l_shashen_gong_mark") > 0
        else
            return player == target and data.to == Player.Start and player:getMark("@l_shashen_gong_mark") > 0
        end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local is_trig = false
    if event == fk.TargetConfirming then
        is_trig = room:askForSkillInvoke(player, self.name, data, "#l_weijian_mark_canceltarget::" .. data.from)
        return is_trig
    else
        if data.to == Player.Start then
            is_trig = room:askForSkillInvoke(player, self.name, data)
        end
        if is_trig then
            player:skip(Player.Judge)
            player:skip(Player.Draw)
            return true
        else
            return false
        end
    end
    
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetConfirming then
        AimGroup:cancelTarget(data, data.to)
        room:removePlayerMark(player, "@l_shashen_gong_mark",1)
    else
        local mark = player:getMark("@l_shashen_gong_mark")
        room:drawCards(player,mark,self.name)
        local slash_num = math.floor(mark/2)
        self.cost_data = 0
        if slash_num > 0 then
            room:setPlayerMark(player,"l_wuan_slash",slash_num)
            self.cost_data = slash_num
        end
        room:setPlayerMark(player,"@l_shashen_gong_mark",0)
    end
    
  end,
  refresh_events = {fk.EventPhaseEnd},
    can_refresh = function (self, event, target, player, data)
        return target == player and player:hasSkill(self.name) and player.phase == Player.Finish
    end,
    on_refresh = function (self, event, target, player, data)
        if self.cost_data and self.cost_data > 0 then
            local room = player.room
            room:loseHp(player,self.cost_data,self.name)
            room:setPlayerMark(player,"l_wuan_slash",0)
            self.cost_data = nil
        end
    end
}

local l_wuan_trig = fk.CreateTargetModSkill{
    name = "#l_wuan_trig",
    residue_func = function(self, player, skill, scope)
        if player:getMark("l_wuan_slash") > 0 and skill.trueName == "slash_skill" and scope == Player.HistoryPhase then
            return player:getMark("l_wuan_slash")
        end
    end,
}

local l_shashen = fk.CreateTriggerSkill{
    name = "l_shashen",
    frequency = Skill.Compulsory,
    events = {fk.DamageCaused},
    can_trigger = function(self, event, target, player, data)
        local room = player.room
        return player:hasSkill(self.name) and data.from == player and player:getMark("@l_shashen_gong_mark") < #room:getAlivePlayers()
    end,
    on_use = function(self, event, target, player, data)
        local room = player.room
        room:addPlayerMark(player,"@l_shashen_gong_mark",1)
    end,
}

local l_weijian = fk.CreateTriggerSkill{
  name = "l_weijian",
  events = {fk.Deathed},
  can_trigger = function(self, event, target, player, data)
    
    return target ~= player and player:hasSkill(self.name) and player.phase == Player.Play and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local alive_target = room:getAlivePlayers()
    if #alive_target > 2 and room:askForSkillInvoke(player, self.name, data)  then
        return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    
    local chs = {"deadsit_more","deadsit_less"}
    local chc = room:askForChoice(player,chs,self.name,"#l_weijian_propmt")
    -- local to_seat = data.to.seat
    local other_players = room:getOtherPlayers(player,false,false)
    local facedown_num = 0
    for key, op in pairs(other_players) do
        if chc == "deadsit_more" then
            if op.seat > target.seat then
                op:turnOver()
            else
                room:setPlayerMark(op,"@@l_weijian_mark",1)
            end
        else
            if op.seat < target.seat then
                op:turnOver()
            else
                room:setPlayerMark(op,"@@l_weijian_mark",1)
            end
        end
        if not op.faceup then
            facedown_num = facedown_num + 1
        end
    end
    local faceup_num = #other_players - facedown_num
    if facedown_num > faceup_num then
        local discard_num = facedown_num - faceup_num
        local play_card_num = #player.player_cards[Player.Hand]+#player.player_cards[Player.Equip]
        if play_card_num > discard_num  then
            room:askForDiscard(player,discard_num,discard_num,true,self.name,false,".","#l_weijian_discard"..discard_num)
        else
            -- room:askForDiscard(player,play_card_num,play_card_num,true,self.name,false,".","#l_weijian_discard"..play_card_num)
            player:throwAllCards("he")
        end
    elseif facedown_num < faceup_num then
        room:drawCards(player,faceup_num - facedown_num,self.name)
    end
  end,
  refresh_events = {fk.EventPhaseEnd},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and player.phase == Player.Start
  end,
  on_refresh = function (self, event, target, player, data)
     local room = player.room
     for key, op in pairs(room:getOtherPlayers(player)) do
        if op:getMark("@@l_weijian_mark") > 0 then
            room:removePlayerMark(op,"@@l_weijian_mark",1)
        end
     end
  end
}

local l_weijian_trig = fk.CreateTriggerSkill{
  name = "#l_weijian_trig",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self.name) then
        local to = player.room:getPlayerById(data.to)
        local mark = to:getMark("@@l_weijian_mark")
        return #AimGroup:getAllTargets(data.tos) == 1 and data.from == player.id and data.card and data.card.trueName == "slash" and mark > 0
    end
    return false
  end,
  on_cost = function(self, event, target, player, data)
    local availableTargets = table.map(table.filter(player.room.alive_players, function(p)
        return p:getMark("@@l_weijian_mark") > 0 and not table.contains(TargetGroup:getRealTargets(data.tos), p.id)
    end), function(p)
        return p.id 
    end)
    if #availableTargets == 0 then return false end
    --   local targets = player.room:askForChoosePlayers(player, availableTargets, 1, #availableTargets, "#l_weijian_mark_addtarget", self.name, true)
    if #availableTargets > 0 then
        self.cost_data = availableTargets
        return true
    end
    return false
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, self.cost_data)
    table.forEach(self.cost_data, function(pid)
        AimGroup:addTargets(room, data, pid)
    end)
  end,
}

local l__baiqi = General(extension, "l__baiqi", "qun", 4)
l_weijian:addRelatedSkill(l_weijian_trig)
l_wuan:addRelatedSkill(l_wuan_trig)
l__baiqi:addSkill(l_wuan)
l__baiqi:addSkill(l_shashen)
l__baiqi:addSkill(l_weijian)
Fk:loadTranslationTable{
  ["l__baiqi"] = "白起",
  ["l_wuan"] = "武安",
  [":l_wuan"] = "准备阶段开始时，若你身上有“功”标记则你可以摸“功”标记数量牌，如此做你跳过判定和摸牌阶段，出牌阶段【杀】次数+X(X为“功”标记数量/2)(向下取整)并移除所有“功”标记，回合结束时失去X体力;当你成为其他角色使用牌目标时，若你有“功”标记，你可以减少1枚“功”标记取消之",
  ["l_shashen"] = "杀神",
  [":l_shashen"] = "锁定技，当你造成伤害，可以获得1枚“功”标记，获得该标记数量不能高于存活目标",
  ["l_weijian"] = "围歼",
  [":l_weijian"] = "限定技，当你于出牌阶段杀死一名角色，你可以根据死亡角色使大于其座位一侧的其他角色翻面，另一侧则获得“围困”标记，当翻面其他角色总数大于正面角色，你弃它们之间的差值的牌，反之你摸差值的牌;当你对“围困”标记角色使用杀，其他有“围困”标记角色也成为杀的目标;你的下回合开始，清除所有“围困”标记",
  ["@@l_weijian_mark"] = "围困",
  ["#l_weijian_mark_canceltarget"] = "是否花费1个“功”标记取消 %dest 的目标",
  ["#l_weijian_mark_addtarget"] = "是否让其他“围困”标记角色也成为目标",
  ["#l_weijian_discard"] = "弃置 %dest 张牌",
  ["#l_weijian_trig"] = "围歼",
  ["@l_shashen_gong_mark"] = "功",
  ["deadsit_more"] = "大于死亡角色座位翻面",
  ["deadsit_less"] = "小于死亡角色座位翻面",
  ["#l_weijian_propmt"] = "选择一侧角色翻面,另一侧角色获得“围困”标记"
}


--刘备
local l_jieyi_proh = fk.CreateProhibitSkill{
  name = "#l_jieyi_proh",
  is_prohibited = function(self, from, to, card)    
    if to:hasSkill(self.name) then
        if from:getMark("@l_rende_givecards") > 0 then
            return true
        end
    end
    if from:hasSkill(self.name) then
        if to:getMark("@l_rende_givecards") > 0 then
            return true
        end
    end
  end,
}

local l_jieyi = fk.CreateTriggerSkill{
  name = "l_jieyi",
  events = {fk.TargetSpecified},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and data.card and data.card.trueName == "slash"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(data.to)
    -- local ren_mark_playerlist = table.map(room:getOtherPlayers(player),function(p) if p:getMark("@l_rende_givecards") > 0 then return p end end)
    local ren_mark_playerlist = {}
    for _, otherplayer in pairs(room:getOtherPlayers(player)) do
        if otherplayer:getMark("@l_rende_givecards") > 0 then
            table.insert(ren_mark_playerlist,otherplayer)
        end
    end
    if #ren_mark_playerlist > 0 then
        self.cost_data = {}
        for key, ren_player in pairs(ren_mark_playerlist) do
            if ren_player:inMyAttackRange(to) then
                table.insert(self.cost_data,{ren_player.id,to.id})
            end
        end
    end
  end,
  refresh_events = {fk.CardUseFinished},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and data.card and data.card.trueName == "slash" and self.cost_data
  end,
  on_refresh = function (self, event, target, player, data)
     local room = player.room
     for key, ren_player in pairs(self.cost_data) do
        local tar = room:getPlayerById(ren_player[1])
        if tar:isAlive() then
            local use = room:askForUseCard(tar, "slash", "slash", "#l_jieyi_ren_mark_useslash::"..ren_player[2], true, {must_targets = {ren_player[2]}})
            if use then
                room:useCard(use)
            end
        end
     end
     self.cost_data = nil
  end
}

local l_rende_playend_trig = fk.CreateTriggerSkill{
  name = "#l_rende_playend_trig",
  mute = true,
  refresh_events = {fk.EventPhaseEnd},
  can_refresh = function(self, event, target, player, data)
    return target == player and player.phase == Player.Play and player:hasSkill(self.name)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "l__rende_cards", 0)
  end,
}
local l_rende_givecard_trig = fk.CreateTriggerSkill{
  name = "#l_rende_givecard_trig",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target ~= player and target.phase == Player.Play and player:hasSkill(self.name) and target:getMark("@l_rende_givecards") > 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    
    if #target.player_cards[Player.Hand] > 0 or #target.player_cards[Player.Equip] > 0  then
        if room:askForSkillInvoke(target, self.name, data) then
            return true
        end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    -- room:setPlayerMark(player, "l__rende_cards", 0)
    local marknum = target:getMark("@l_rende_givecards")
    local cards = room:askForCard(target,1,marknum,true,self.name,true,".","#l_rende_givecard::"..player.id)
    if #cards > 0 then
        room:broadcastSkillInvoke(self.name, 1)
        room:notifySkillInvoked(player, self.name)
        local dummy = Fk:cloneCard("dilu")
        dummy:addSubcards(cards)
        room:obtainCard(player,dummy,false,fk.ReasonGive)
        if #cards >= marknum and player:isWounded() then
            room:recover({
                who = player,
                num = 1,
                recoverBy = player,
                skillName = self.name
            })
        end
        room:removePlayerMark(target,"@l_rende_givecards",marknum)
    end
  end,
}
local l_rende = fk.CreateActiveSkill{
    name = "l_rende",
    anim_type = "support",
    card_filter = function(self, to_select, selected)
        -- local room = 
        return Fk:currentRoom():getCardArea(to_select) ~= Card.PlayerEquip
    end,
    target_filter = function(self, to_select, selected)
        local room = Fk:currentRoom()
        local target = room:getPlayerById(to_select)
        return #selected == 0 and to_select ~= Self.id and target:getMark("@l_rende_givecards") == 0 
    end,
    min_card_num = 1,
    on_use = function(self, room, effect)
        local target = room:getPlayerById(effect.tos[1])
        local player = room:getPlayerById(effect.from)
        local cards = effect.cards
        local marks = player:getMark("l__rende_cards")
        local dummy = Fk:cloneCard'slash'
        dummy:addSubcards(cards)
        room:obtainCard(effect.tos[1], dummy, false, fk.ReasonGive)

        local maxmark = 0
        for key, op in pairs(room:getOtherPlayers(player)) do
            local mark = op:getMark("@l_rende_givecards")
            if maxmark < mark  then
                maxmark = mark
                -- oplayer = op
            end
        end
        if #cards - maxmark > 0 then
            room:setPlayerMark(target, "@l_rende_givecards", #cards)
            if #cards - maxmark > 1 then
                room:drawCards(player,1,self.name)
            end
        end
        room:setPlayerMark(player, "l__rende_cards", #cards)
        if marks < 2 and marks + #cards >= 2 then
            local card = Fk:cloneCard("slash")
            local n = card.skill:getMaxUseTime(Self, Player.HistoryPhase, card,Self)
            local history_slash = player:usedCardTimes("slash",Player.HistoryPhase)
            if history_slash >= n then
                return
            end
            local opidlist = {}
            for key, op in pairs(room:getOtherPlayers(player)) do
                if player:inMyAttackRange(op) then
                    table.insert(opidlist,op.id)
                end
            end
            
            local tars = room:askForChoosePlayers(player,opidlist,1,1,"#l_rende_slash",self.name,true)
            if #tars > 0 then
                local chc = room:askForChoice(player,{"slash","thunder__slash","fire__slash"},self.name)
                room:useVirtualCard(chc,nil,player,room:getPlayerById(tars[1]),self.name)
            end
        end
    end,
}
-- local l__liubei = General(extension, "l__liubei", "shu", 4)
-- l_rende:addRelatedSkill(l_rende_playend_trig)
-- l_rende:addRelatedSkill(l_rende_givecard_trig)
-- l_jieyi:addRelatedSkill(l_jieyi_proh)
-- l__liubei:addSkill(l_rende)
-- l__liubei:addSkill(l_jieyi)
-- Fk:loadTranslationTable{
--   ["l__liubei"] = "刘备",
--   ["l_rende"] = "仁望",
--   [":l_rende"] = "出牌阶段，你可以将任意手牌交给没有“仁”标记的其他角色若其拿到手牌数满足以下条件则获得对应效果：<br/>1.大于X，其获得等同于拿到手牌数的“仁”标记.<br/>2.若给出手牌数大于x+1，你摸一张牌;<br/>若以此法给出的手牌大于1你可以视为使用一张某种属性【杀】;<br/>当持有“仁”标记的角色出牌阶段开始时，其可以交给你至多y张牌，如此做移除身上所有的“仁”标记;若其交给你的牌等y你回复1点体力;(x为场上最多的“仁”标记数量，y为该角色持有“仁”标记数量)",
--   ["l_jieyi"] = "结义",
--   [":l_jieyi"] = "锁定技，你不能对持有“仁”标记的角色为目标或其不能指定你为目标使用牌;当你对其他角色使用唯一目标的杀结算后，该角色在持有“仁”标记角色攻击范围内时，其可以依次对目标角色使用一张【杀】",
--   ["@l_rende_givecards"] = "仁",
--   ["#l_rende_givecard_trig"] = "仁德",
--   ["#l_rende_givecard"] = "仁德：选择交给 %dest 的牌",
--   ["thunder_slash"] = "雷杀",
--   ["fire_slash"] = "火杀",
--   ["#l_rende_slash"] = "是否对其他人出杀",
--   ["#l_jieyi_ren_mark_useslash"] = "是否对 %dest 出杀",
-- }
--饶岳
local l_yimou = fk.CreateTriggerSkill{
    name = "l_yimou",
    anim_type = "",
    events = {fk.EventPhaseStart},
    can_trigger = function (self, event, target, player, data)
        if player == target and player:hasSkill(self.name) and player.phase == Player.Start then
            if not player.tag[self.name] then
                return true
            else
                if #player.tag[self.name] == 0 then
                    return false
                else
                    return true
                end
            end
        else
            return false
        end 
    end,
    on_cost = function(self, event, target, player, data)
        local room = player.room
        if room:askForSkillInvoke(player, self.name, data) then
            return true
        end
        -- self.cancel_cost = true
    end,
    on_use = function(self, event, target, player, data)
        local room = player.room
        local targets = room:askForChoosePlayers(player,table.map(player.room:getOtherPlayers(player), function (p)
        return p.id end), 1, 1, "选择对象", self.name)
        player.tag[self.name] = player.tag[self.name] or {"draw1_kill1","damage1_hand+1","discard1_hand-1"}
        local chs = player.tag[self.name]
        if #targets > 0 and #chs > 0 then
            local tar = room:getPlayerById(targets[1])
            local chc = room:askForChoice(player,chs,self.name)
            --记录上次选择的人物和选项
            local clochc = self.cost_data and table.clone(self.cost_data) or {}
            local prompt
            if chc == "draw1_kill1" then
                tar:drawCards(1,self.name)
                prompt = "@@yimou_choose1"
            elseif chc == "damage1_hand+1" then
                room:damage{
                    from = nil,
                    to = tar,
                    damage = 1,
                    skillName = self.name,
                }
                tar:drawCards(2,self.name)
                prompt = "@@yimou_choose2"
            else
                room:askForDiscard(tar,1,1,true,self.name,false)
                prompt = "@@yimou_choose3"                
            end
            room:setPlayerMark(tar,prompt,1)
            self.cost_data = {}
            table.insert(self.cost_data,targets[1])
            table.insert(self.cost_data,prompt)

            if #clochc > 0 then
                local islast = table.contains(clochc,targets[1]) or table.contains(clochc,prompt)
                if islast then
                    -- "指向上个相同的人或者相同技能删除选项"
                    table.removeOne(player.tag[self.name],chc)
                end
            end

        end
    end,
    refresh_events = {fk.EventPhaseEnd},
    can_refresh = function (self, event, target, player, data)
        if target.phase == Player.Finish and player:hasSkill(self.name) and self.cost_data and self.cost_data[2] then
            if target:getMark(self.cost_data[2]) > 0 then
                return true
            end
        end
    end,
    on_refresh = function (self, event, target, player, data)
        local room = player.room
        if self.cost_data and #self.cost_data > 0 then
            room:removePlayerMark(target,self.cost_data[2],1)
        end
    end
}

local yimouchoose1_targetmod = fk.CreateTargetModSkill{
    name = "#yimouchoose1_targetmod",
    residue_func = function(self, player, skill, scope)
        if player:getMark("@@yimou_choose1") > 0 and skill.trueName == "slash_skill" and scope == Player.HistoryPhase then
            return player:getMark("@@yimou_choose1")
        end
    end,
}

local yimouchoose2_maxcards = fk.CreateMaxCardsSkill{
    name = "#yimouchoose2_maxcards",
    correct_func = function(self, player)
        if player:getMark("@@yimou_choose2") > 0 then
            return player:getMark("@@yimou_choose2")
        end
    end,
}

local yimouchoose3_maxcards = fk.CreateMaxCardsSkill{
    name = "#yimouchoose3_maxcards",
    correct_func = function(self, player)
        if player:getMark("@@yimou_choose3") > 0 then
            return -1
        end
    end,
}

local qinwei = fk.CreateTriggerSkill{
    name = "qinwei",
    anim_type = "",
    events = {fk.AfterDrawNCards,fk.EventPhaseEnd},
    can_trigger = function (self, event, target, player, data)
        if player == target and player:hasSkill(self.name) and player.tag["l_yimou"] and #player.tag["l_yimou"] > 0 then
            if event == fk.AfterDrawNCards then
                return true
            end
            if player.phase == Player.Play then
                return true
            end
            return false
        end
    end,
    on_cost = function (self, event, target, player, data)
        local room = player.room
        if event == fk.AfterDrawNCards then
            return room:askForSkillInvoke(player, self.name, data)
        end
        if player.phase == Player.Play and self.remainchs and #self.remainchs then
            return true
        end
    end,
    on_use = function (self, event, target, player, data)
        local room = player.room
        local hanDleChoice = function (choices)
            local chc = room:askForChoice(player,choices,self.name)
            local prompt
            if chc == "draw1_kill1" then
                prompt ="@@yimou_choose1"
                player:drawCards(1,self.name)
            elseif chc == "damage1_hand+1" then
                prompt ="@@yimou_choose2"
                room:damage{
                    from = nil,
                    to = player,
                    damage = 1,
                    skillName = self.name,
                }
                player:drawCards(2,self.name)
            else
                prompt ="@@yimou_choose3"
                room:askForDiscard(player,1,1,true,self.name,false)
            end
            room:setPlayerMark(player,prompt,1)
            table.insert(self.ymmark,prompt)
            return chc
        end

        if event == fk.AfterDrawNCards then
             local nodelchc = {}
              self.ymmark = {}
            for key, chc in pairs({"draw1_kill1","damage1_hand+1","discard1_hand-1"}) do
                local nodel = table.contains(player.tag["l_yimou"],chc)
                if nodel then
                    table.insert(nodelchc,chc)
                end
            end
            
            local chc = hanDleChoice(nodelchc)
            table.removeOne(nodelchc,chc)
            self.remainchs = table.clone(nodelchc) or {}
        end
        if player.phase == Player.Play then
            if #self.remainchs > 0 then
                local prompt
                for i = 1, #self.remainchs do
                    -- hanDleChoice(self.remainchs)player
                    if self.remainchs[i] == "draw1_kill1" then
                        prompt ="@@yimou_choose1"
                        player:drawCards(1,self.name)
                    elseif self.remainchs[i] == "damage1_hand+1" then
                        prompt ="@@yimou_choose2"
                        room:damage{
                            from = nil,
                            to = player,
                            damage = 1,
                            skillName = self.name,
                        }
                        player:drawCards(2,self.name)
                    else
                        prompt ="@@yimou_choose3"
                        room:askForDiscard(player,1,1,true,self.name,false)
                    end
                    room:setPlayerMark(player,prompt,1)
                    table.insert(self.ymmark,prompt)
                    end
                end
        end

    end,
    refresh_events = {fk.EventPhaseEnd},
    can_refresh = function (self, event, target, player, data)
        if player == target and player:hasSkill(self.name) and player.phase == Player.Finish then
            if player:getMark("@@yimou_choose1") > 0 or player:getMark("@@yimou_choose2") > 0 or player:getMark("@@yimou_choose3") > 0 then
                return true
            end
            return false
        end
        return false
    end,
    on_refresh = function (self, event, target, player, data)
        local room = player.room
        for key, mark in pairs(self.ymmark) do
            room:removePlayerMark(player,mark,1)
        end
        
    end,
}

local l__raoyue = General(extension, "l__raoyue", "wei", 4)
l_yimou:addRelatedSkill(yimouchoose1_targetmod)
l_yimou:addRelatedSkill(yimouchoose2_maxcards)
l_yimou:addRelatedSkill(yimouchoose3_maxcards)
l__raoyue:addSkill(l_yimou)
l__raoyue:addSkill(qinwei)
Fk:loadTranslationTable{
    ["l__raoyue"] = "饶岳",
    ["l_yimou"] = "异谋",
    ["draw1_kill1"] = "摸1,杀+1",
    ["damage1_hand+1"] = "1伤，摸2，手上+1",
    ["discard1_hand-1"] = "弃1,手上-1",
    ["qinwei"] = "亲为",
    ["@@yimou_choose1"] = "异谋1",
    ["@@yimou_choose2"] = "异谋2",
    ["@@yimou_choose3"] = "异谋3",
    [":qinwei"] = "摸牌阶段结束时，你可执行“异谋”中未被删除的一项，若如此做本回合出牌阶段结束时你依次执行“异谋”中未被删除的其余项",
    [":l_yimou"] = "准备阶段，你可选择一项令一名其他角色执行：<br/>1：摸一张牌，其下个出牌阶段可多使用一张【杀】；<br/>2：受到1点无来源伤害并摸2张牌，其下个弃牌阶段手牌上限+1；<br/>3：弃置一张牌，其下个弃牌阶段手牌上限-1；然后若此技能的目标角色或选项与上一回合此技能相同，你删除此选项",
    
}

--张飞
local l_yangzui = fk.CreateActiveSkill{
    name = "l_yangzui",
    anim_type = "",
    pattern = "analeptic",
    can_use = function(self, player)
        return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
    end,
    card_filter = function(self, to_select, selected)
        return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeBasic
    end,
    min_card_num = 1,
    on_use = function(self, room, effect)
        local player = room:getPlayerById(effect.from)
        room:throwCard(effect.cards, self.name, player)
        room:loseHp(player,1,self.name)
        room:useVirtualCard("analeptic", nil, player, player, self.name)
        room:drawCards(player,1,self.name);
        room:setPlayerMark(player, "l_yangzui_slash-turn", player:getLostHp())
    end,
}

local l_yangzui_tri = fk.CreateTriggerSkill{
    name = "#l_yangzui_tri",
    anim_type = "",
    events = {fk.EnterDying},
    can_trigger = function(self, event, target, player, data)
        return player:hasSkill("l_yangzui") and player:usedSkillTimes("l_yangzui", Player.HistoryPhase) == 1 and
         player:hasSkill(self.name) and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and data.damage and data.damage.card and data.damage.card.trueName == "slash"
    end,
    on_use = function(self, event, target, player, data)
        if player:getLostHp() == 0 then
            player.room:drawCards(player, 2, self.name)
            return
        end
        local chs = {"recover","draw2"}
        local room = player.room
        local chc = room:askForChoice(player,chs,self.name)
        if chc == "recover" then
            room:recover{
                who = player,
                num = 1,
                recoverBy = player,
                skillName = self.name
            }
        else
            room:drawCards(player, 2, self.name)
        end
    end,
}
    

local l_hanmang = fk.CreateActiveSkill{
    name = "l_hanmang",
    anim_type = "",
    can_use = function(self, player)
        return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
    end,
    card_filter = function(self, to_select, selected)
        return Fk:getCardById(to_select).type == Card.TypeEquip
    end,
    min_card_num = 1,
    on_use = function(self, room, effect)
        local player = room:getPlayerById(effect.from)
        room:throwCard(effect.cards, self.name, player)
        room:setPlayerMark(player, "l_hanmang_extra-turn", #effect.cards)
    end,
}

local l_yibing = fk.CreateFilterSkill{
  name = "l_yibing",
  event = {},
  card_filter = function(self, card, player)
    return player:hasSkill(self.name) and card.type == Card.TypeTrick
  end,
  view_as = function(self, card)
    return Fk:cloneCard("slash", card.suit, card.number)
  end,
}

local l_hanmang_targetmod = fk.CreateTargetModSkill{
  name = "#l_hanmang_targetmod",
  extra_target_func = function(self, player, skill)
    if skill.trueName == "slash_skill" and player:getMark("l_hanmang_extra-turn") > 0 then
      return player:getMark("l_hanmang_extra-turn")
    end
  end,
}

local l_yangzui_targetmod = fk.CreateTargetModSkill{
    name = "#l_yangzui_targetmod",
    distance_limit_func =  function(self, player, skill)
    if skill.trueName == "slash_skill" and player:getMark("l_yangzui_slash-turn") > 0 then
      return player:getLostHp()
    end
  end,
    residue_func = function(self, player, skill, scope)
        if player:getMark("l_yangzui_slash-turn") > 0 and skill.trueName == "slash_skill" and scope == Player.HistoryPhase then
            return player:getMark("l_yangzui_slash-turn")
        end
    end,
}

local l__zhangfei = General(extension, "l__zhangfei", "shu", 4)
l_hanmang:addRelatedSkill(l_hanmang_targetmod)
l_yangzui:addRelatedSkill(l_yangzui_targetmod)
l_yangzui:addRelatedSkill(l_yangzui_tri)
l__zhangfei:addSkill(l_yangzui)
l__zhangfei:addSkill(l_hanmang)
l__zhangfei:addSkill(l_yibing)
Fk:loadTranslationTable{
    ["l__zhangfei"] = "张飞",
    ["l_yangzui"] = "佯醉",
    ["#l_yangzui_tri"] = "佯醉",
    [":l_yangzui"] = "出牌阶段限一次，你可以失去1点体力并弃掉1张基本牌视为使用【酒】，若如此做摸1张牌，本回合你使用【杀】的次数+X且攻击距离+X（X为你已损失体力值）；当有角色因你的【杀】而进入濒死时，你可以摸2张牌或回复一点体力（每回合限1次）",
    ["l_hanmang"] = "飙莽",
    [":l_hanmang"] = "出牌阶段限一次，你可以弃置X张装备并使本回合你使用的【杀】可多指定至多X名目标",
    ["l_yibing"] = "疑兵",
    [":l_yibing"] = "锁定技：你的锦囊牌均视为【杀】",
    
}

-- 孙策
local l_weinan = fk.CreateTriggerSkill {
    name = "l_weinan",
    anim_type = "",
    events = {fk.EventPhaseStart},
    can_trigger = function(self, event, target, player, data)
        return target ~= player and player:hasSkill(self.name) and target.phase == Player.Start
    end,
    on_cost = function(self, event, target, player, data)
        local room = player.room
        if room:askForSkillInvoke(player, self.name, data) then
            return true
        end
        -- self.cancel_cost = true
    end,
    on_use = function(self, event, target, player, data)
        local room = player.room
        local chs = {"Cancel","loseHp"}
        if player:isWounded() then
            table.insert(chs, "recover")
        end
        if player:isNude() then
            table.removeOne(chs,"recover")
        end
        --觉醒了
        if player:usedSkillTimes("l_hunshang", Player.HistoryGame) > 0 then
            room:loseHp(player, 1, self.name)
            room:drawCards(player, 1, self.name)
        elseif player:usedSkillTimes("l_hunshang", Player.HistoryGame) == 0 then
            local chc = room:askForChoice(player, chs, self.name)
            if chc == "Cancel" then
                return
            end
            if chc == "recover" then
                room:recover{
                    who = player,
                    num = 1,
                    recoverBy = player,
                    skillName = self.name
                }
                room:askForDiscard(player, 1, 1, true, self.name, false);
            else
                room:loseHp(player, 1, self.name)
                room:drawCards(player, 1, self.name)
            end
        end
        
        if target:isKongcheng() or player:isKongcheng() then
            return
        end

        local pindian = player:pindian({target}, self.name)
        if pindian.results[target.id].winner == player then
            -- room:useVirtualCard("slash", nil, player, target, self.name, true)
            local selects = {"l_weinan_slash", "l_weinan_duel", "l_weinan_snatch"}
            local isAddSelect = false
            local minValue = 1
            if player:usedSkillTimes("l_hunshang", Player.HistoryGame) > 0 then
                isAddSelect = true
                minValue = 2
            end

            for i = math.max(player:getLostHp(), minValue), 1, -1 do
                if #selects <= 0 or target.dead then return end;
                local select = room:askForChoice(player, selects, self.name)
                if isAddSelect then
                    table.removeOne(selects,select)
                    isAddSelect = false
                else
                    selects = {}
                end
                
                if select == "l_weinan_slash" then
                    room:useVirtualCard("slash", nil, player, target, self.name, true)
                elseif select == "l_weinan_duel" then
                    local duel = Fk:cloneCard("duel")
                    room:useCard({
                        card = duel,
                        from = player.id,
                        tos = {{target.id}}
                    })
                elseif select == "l_weinan_snatch" then
                    player.room:useVirtualCard("snatch", nil, player, target, self.name)
                end
            end

        else
            -- room:askForDiscard(player,1,1,true,self.name,false);
            if player:isNude() then
              return
            end
            local discard_player = room:askForCardsChosen(target, player, 1, 1, "hej", self.name)
            room:throwCard(discard_player, self.name, player, target)
            if player:usedSkillTimes("l_hunshang", Player.HistoryGame) > 0 then
                room:damage{
                    from = target,
                    to = player,
                    damage = 1,
                    skillName = self.name,
                }
            end
        end

    end
}

local l_kaixuan = fk.CreateTriggerSkill{
  name = "l_kaixuan",
  frequency = Skill.Compulsory,
  events = {fk.PindianCardsDisplayed},
  can_trigger = function(self, event, target, player, data)
    if data.from == player or player == data.to then
        return player:hasSkill(self.name)
    end
  end,
  on_use = function(self, event, target, player, data)
    
     if data.from == player then
        -- "浪孙策拼别人变点数"
        local red_pindian_num = player:getMark("l_hunshang_mody_pd") == 0 and 8 or 9
        if data.fromCard.color == Card.Red and data.fromCard.number < red_pindian_num then
            data.fromCard.number = red_pindian_num + player:getLostHp()
        end
    else
        --"别人拼浪孙策变点数"
        local red_pindian_num = player:getMark("l_hunshang_mody_pd") == 0 and 8 or 9
        if player == data.to and data.results[player.id].toCard == Card.Red and data.results[player.id].toCard.number < red_pindian_num then
            data.results[player.id].toCard.number = red_pindian_num + player:getLostHp()
        end
    end
     
  end,
}

local l_hunshang = fk.CreateTriggerSkill{
  name = "l_hunshang",
  frequency = Skill.Wake,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and
      player:usedSkillTimes(self.name, Player.HistoryGame) == 0 and
      player.phase == Player.Start
  end,
  can_wake = function(self, event, target, player, data)
    return player.hp == 1 or #player.player_cards[Player.Hand] < 2;
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player,"l_hunshang_maxhand",1)
    room:setPlayerMark(player,"l_hunshang_mody_pd",1)
    room:changeMaxHp(player, 1)
    if player:isWounded() then
        room:drawCards(player,player:getLostHp(),self.name)
        room:recover({
        who = player,
        num = player:getLostHp(),
        recoverBy = player,
        skillName = self.name
      })
    end
  end,
}

local l_hunshang_trig = fk.CreateMaxCardsSkill{
  name = "#l_hunshang_trig",
  fixed_func = function (self, player)
    if player:hasSkill(self.name) and player:getMark("l_hunshang_maxhand") > 0 then
      return player:getLostHp()
    end
  end,
}

local l__sunce = General(extension, "l__sunce", "wu", 4)
l__sunce:addSkill(l_weinan)
l__sunce:addSkill(l_kaixuan)
l__sunce:addSkill(l_hunshang)
-- l__sunce:addSkill(l_hunshang_trig)
l_weinan:addRelatedSkill(l_hunshang_trig)
Fk:loadTranslationTable{
    ["l__sunce"] = "孙策",
    ["l_weinan"] = "平南",
    [":l_weinan"] = "其他角色准备阶段开始时，你可以选择弃1张牌回1血或失去1体力摸1张牌(觉醒后必定触发此选项)，如果以此法且双方都有手牌则对该角色进行拼点，当你拼赢从视为出【杀】，视为【决斗】，视为【顺手牵羊】选项中选择一项(觉醒后可以依次选择两项)，否则视为其弃你区域一张牌(觉醒后增加其对你造成1点伤害)",
    ["l_kaixuan"] = "凯旋",
    [":l_kaixuan"] = "锁定技，你的红色拼点牌小于8(觉醒后改为9)时视为8+x(x为损失体力值，觉醒后改为9+x)",
    ["l_hunshang"] = "魂落",
    [":l_hunshang"] = "觉醒技，准备阶段，当你体力值为1或者手牌少于2，增加1体力上限并摸X张牌(X为你的损失体力值)后回满血，修改【平南】和【凯旋】技能且手牌上限改为损失体力值",
    ["l_weinan_slash"] = "视为使用【杀】",
    ["l_weinan_duel"] = "视为使用【决斗】",
    ["l_weinan_snatch"] = "视为使用【顺手牵羊】",
    ["l_hunshang_trig"] = "魂落"
}

local extension_card = Package:new("lang_cards", Package.CardPack)
extension_card.extensionName = "replace_rec"
extension.game_modes_blacklist = {"m_1v1_mode", "m_1v2_mode", "m_2v2_mode", "zombie_mode", "heg_mode"}
extension.game_modes_whitelist = {"hulao_mode"}

--重写飞扬跋扈
local l_feiyang = fk.CreateTriggerSkill{
  name = "l_feiyang",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and
      player.phase == Player.Judge and
      #player:getCardIds(Player.Hand) >= 2 and
      #player:getCardIds(Player.Judge) > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:askForDiscard(player, 2, 2, false, self.name, false)
    local card = room:askForCardChosen(player, player, "j", self.name)
    room:throwCard(card, self.name, player, player)
  end
}
Fk:addSkill(l_feiyang)
local l_bahubuff = fk.CreateTargetModSkill{
  name = "#l_bahubuff",
  residue_func = function(self, player, skill, scope)
    if player:hasSkill(self.name) and skill.trueName == "slash_skill"
      and scope == Player.HistoryPhase then
      return 1
    end
  end,
}
local l_bahu = fk.CreateTriggerSkill{
  name = "l_bahu",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and
      player.phase == Player.Start
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1)
  end,
}
l_bahu:addRelatedSkill(l_bahubuff)
Fk:addSkill(l_bahu)

local yx_yvxi_skill = fk.CreateTriggerSkill{
  name = "#yx_yvxi_skill",
  attached_equip = "yx_yvxi",
}
Fk:addSkill(yx_yvxi_skill)
local yx_yvxi = fk.CreateTreasure{
  name = "yx_yvxi",
  suit = Card.Heart,
  number = 6,
  equip_skill = yx_yvxi_skill,
  on_install = function(self, room, player)
    if player:isAlive() and self.equip_skill:isEffectable(player) then
      room:handleAddLoseSkills(player,"l_feiyang|l_bahu", nil, true, false)
    end
  end,
  on_uninstall = function(self, room, player)
    if not player then return end
    if player:isAlive() and self.equip_skill:isEffectable(player) then
      if player:hasSkill("l_kuixi") then
        player:throwAllCards("he")
      end
      room:handleAddLoseSkills(player,"-l_feiyang|-l_bahu", nil, true, false)
    end
  end,
}
extension_card:addCards{yx_yvxi}

Fk:loadTranslationTable{
  ["lang_cards"] = "浪包卡组",
  ["yx_yvxi"] = "玉玺",
  [":yx_yvxi"] = "装备牌·宝物<br /><b>技能</b>：锁定技：你视为拥有【飞扬】【跋扈】",
  ["#yx_yvxi_skill"] = "玉玺",
  ["l_feiyang"] = "飞扬",
  [":l_feiyang"] = "判定阶段开始时，你可以弃置两张手牌，然后弃置自己判定区的一张牌。",
  ["l_bahu"] = "跋扈",
  [":l_bahu"] = "锁定技，准备阶段，你摸一张牌；出牌阶段，你可以多使用一张【杀】。",
}

--虎牢关卡组
--玲珑狮蛮带
local llsmd_skill = fk.CreateTriggerSkill {
  name = "#llsmd_skill",
  attached_equip = "llsmd",
  events = { fk.TargetConfirming },
  can_trigger = function(self, event, target, player, data)
    
    return player:hasSkill(self.name) and data.to == player.id and data.from ~= data.to and  data.card and #AimGroup:getAllTargets(data.tos) == 1 and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = target.room
    
    if room:askForSkillInvoke(target, self.name, data) then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(target, self.name, "masochism")
    local judge = {
      who = target,
      reason = "#llsmd_skill",
      pattern = ".|.|heart",
    }
    room:judge(judge)
    local result = judge.card
    if result.suit == Card.Heart then
      AimGroup:cancelTarget(data, data.to)
    end
  end,
}
Fk:addSkill(llsmd_skill)

local llsmd = fk.CreateArmor {
  name = "&llsmd",
  suit = Card.Club,
  number = 1,
  equip_skill = llsmd_skill,
}

extension_card:addCards({
  llsmd,
})
Fk:loadTranslationTable {
  ["llsmd"] = "玲珑狮蛮带",
  [":llsmd"] = "装备牌·防具<br /><b>防具技能</b>每回合限一次，当你成为单体牌的目标时，你可以进行判定，若为红桃，取消之",
  ["#llsmd_skill"] = "玲珑狮蛮带",
}

--无双方天画戟
local wxfthj_skill = fk.CreateTriggerSkill {
  name = "#wxfthj_skill",
  attached_equip = "wxfthj",
  anim_type = "offensive",
  events = { fk.Damaged },
  can_trigger = function(self, event, target, player, data)
    
    return player ~= target and player:hasSkill(self.name) and data.from == player and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and
        data.card and data.card.trueName == "slash"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    
    local chc = {"draw_1","discard_1"}
    if data.to.dead then
        table.remove(chc,2)
    end
    local chs = room:askForChoice(player,chc,self.name)
    if chs == "draw_1" then
        room:drawCards(player,1,self.name)
    else
        if not data.to:isNude() then
            -- room:askForDiscard(data.to,1,1,true,self.name,false)
            local cards = room:askForCardsChosen(player,data.to,1,1,"he",self.name)
            if #cards > 0 then
                room:throwCard(cards, self.name, data.to, player)
            end
        end
    end
    room:notifySkillInvoked(player, self.name, "defensive")
  end,
}
Fk:addSkill(wxfthj_skill)

local wxfthj = fk.CreateWeapon {
  name = "&wxfthj",
  suit = Card.Club,
  number = 1,
  attack_range = 4,
  equip_skill = wxfthj_skill,
}
extension_card:addCards({
  wxfthj,
})
Fk:loadTranslationTable {
  ["wxfthj"] = "无双方天画戟",
  [":wxfthj"] = "武器牌·武器<br /><b>攻击范围</b>：4<br /><b>武器技能</b>：每回合限一次，你使用【杀】造成伤害后，你可以摸一张牌或者弃之其一张牌",
  ["#wxfthj_skill"] = "无双方天画戟",
  ["draw_1"] = "摸1张牌",
  ["discard_1"] = "弃其1张牌",
}

--修罗神话吕布装备
--神话方天画戟
local shfthj_skill = fk.CreateTriggerSkill {
  name = "#shfthj_skill",
  attached_equip = "shfthj",
--   anim_type = "offensive",
  -- frequency = Skill.Compulsory,
  events = { fk.TargetConfirmed },
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self.name) and data.from == player.id and #AimGroup:getAllTargets(data.tos) == 1 and data.card and (data.card.trueName == "slash" or data.card.name == "duel")
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if room:askForSkillInvoke(player, self.name, data) then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local target = room:getPlayerById(data.to)
    room:notifySkillInvoked(player, self.name, "offensive")
    local availableTargets = {}
    local othertarget = TargetGroup:getRealTargets(data.tos)
    for _, p in ipairs(room:getOtherPlayers(player)) do
      if not table.contains(othertarget, p.id) and not GensLimts:isSameCamp(player,p) then
        table.insert(availableTargets,p.id)
      end
    end
    
    local chc = {"draw_dis_1"}
    if #availableTargets > 0 then
      table.insert(chc,"addrandtar")
    end
    local chs = room:askForChoice(player,chc,self.name)
    if chs == "draw_dis_1" then
      room:drawCards(player,1,self.name)
      if not target:isNude() then
        local card = room:askForCardChosen(player, target, "he", self.name)
        room:throwCard(card, self.name, target, player)
      end
    else
      local randpids = table.random(availableTargets,1)
      if randpids and #randpids > 0 then
          room:doIndicate(player.id, randpids)
          table.forEach(randpids, function(pid)
              AimGroup:addTargets(room, data, pid)
          end)
      end
    end
  end,
}
Fk:addSkill(shfthj_skill)

local shfthj = fk.CreateWeapon {
  name = "&shfthj",
  suit = Card.Club,
  number = 6,
  attack_range = 4,
  equip_skill = shfthj_skill,
}
extension_card:addCards({
  shfthj,
})
Fk:loadTranslationTable {
  ["shfthj"] = "神话方天画戟",
  [":shfthj"] = "武器牌·武器<br /><b>攻击范围</b>：4<br /><b>武器技能</b>：你使用【杀】或【决斗】指向单一目标后，你可以选择：1.摸1牌并弃其1张牌。2.随机一名其他阵营角色也成为【杀】或【决斗】目标",
  ["#shfthj_skill"] = "神话方天画戟",
  ["addrandtar"] = "随机一名其他不同阵营的角色",
  ["draw_dis_1"] = "摸1张牌，弃其1张牌",
}

local shsfzjg_skill = fk.CreateTriggerSkill {
  name = "#shsfzjg_skill",
  attached_equip = "shsfzjg",
--   anim_type = "offensive",
  -- frequency = Skill.Compulsory,
  events = { fk.EventPhaseStart },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name) and player.phase == Player.Play
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if room:askForSkillInvoke(player, self.name, data) then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, self.name, "offensive")
    local pids = table.filter(room:getOtherPlayers(player), function (pr)
      if not GensLimts:isSameCamp(player,pr) then
        return true
      end
    end)
    pids = table.map(pids,Util.IdMapper)
    local to = table.random(pids)
    if #pids > 0 then
      room:doIndicate(player.id, {to})
      local tar = room:getPlayerById(to)
      room:damage { from = player, to = tar, damage = 1, skillName = self.name }
      local total_cards = tar:getCardIds{Player.Hand, Player.Equip}
      room:throwCard(table.random(total_cards,1),self.name, tar, player)
    end
  end,
}

Fk:addSkill(shsfzjg_skill)
local shsfzjg = fk.CreateTreasure {
  name = "&shsfzjg",
  suit = Card.Spade,
  number = 6,
  equip_skill = shsfzjg_skill,
}
extension_card:addCard(shsfzjg)

Fk:loadTranslationTable {
  ["shsfzjg"] = "神话束发紫金冠",
  [":shsfzjg"] = "装备牌·宝物<br /><b>宝物技能</b>：出牌阶段，你可以对一名其他阵营角色造成一点伤害并随机弃其一张牌。",
  ["#shsfzjg_skill"] = "神话束发紫金冠",
  ["#shsfzjg-choose"] = "神话束发紫金冠：你可以对一名其他角色造成一点伤害并随机弃其一张牌。",
}

--神话吞天铠
local shttk_skill = fk.CreateTriggerSkill {
  name = "#shttk_skill",
  attached_equip = "shttk",
--   anim_type = "support",
  -- frequency = Skill.Compulsory,
  events = { fk.TargetConfirming,fk.Damaged },
  can_trigger = function(self, event, target, player, data)
    
    if event == fk.TargetConfirming then
      return player:hasSkill(self.name) and data.to == player.id and data.from ~= data.to and  data.card and not data.card:isVirtual() and #AimGroup:getAllTargets(data.tos) == 1 and player:usedSkillTimes(self.name, Player.HistoryTurn) < 2
    else
      return player:hasSkill(self.name) and player == target
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    -- room:notifySkillInvoked(target, self.name, "masochism")
    room:notifySkillInvoked(player, self.name, "defensive")
    if event == fk.TargetConfirming then
      local hand_cards = player.player_cards[Player.Hand]
      if data.card.color == Card.Red then
        local red_cards = {}
        table.forEach(hand_cards,function(cid)
          if Fk:getCardById(cid).color == Card.Red then
              table.insert(red_cards,cid)
          end
        end)
        if #red_cards > 1 then
          room:throwCard(table.random(red_cards,2), self.name, player, player)
          room:damage { from = player, to = room:getPlayerById(data.from), damage = 1, skillName = self.name }
        end
      elseif data.card.color == Card.Black then
        local black_cards = {}
        table.forEach(hand_cards,function(cid)
          if Fk:getCardById(cid).color == Card.Black then
              table.insert(black_cards,cid)
          end
        end)
        if #hand_cards > 0 then
          room:throwCard(table.random(black_cards,1), self.name, player, player)
          local to = room:getPlayerById(data.from)
          local total_cards = {}
          table.forEach(to.player_cards[Player.Hand],function(cid)
              table.insert(total_cards,cid)
          end)
          table.forEach(to.player_cards[Player.Equip],function(cid)
              table.insert(total_cards,cid)
          end)
          room:throwCard(table.random(total_cards,1), self.name, to, player)
        end
      end
    else
      room:drawCards(player,data.damage,self.name)
    end
  end,
}
Fk:addSkill(shttk_skill)

local shttk = fk.CreateArmor {
  name = "&shttk",
  suit = Card.Heart,
  number = 6,
  equip_skill = shttk_skill,
}

extension_card:addCards({
  shttk,
})
Fk:loadTranslationTable {
  ["shttk"] = "神话吞天铠",
  [":shttk"] = "装备牌·防具<br /><b>防具技能</b>每回合限两次，当你成为非虚拟单体牌的目标时，若牌的颜色为红色，你随机弃两张红色手牌对其造成1点伤害，若为黑色，你弃一张黑色手牌随机弃其一张牌；每当你受到伤害时，摸受到伤害值的牌",
  ["#shttk_skill"] = "神话吞天铠",
}
--伏魔金刚杵
local fm_jingang_Skill = fk.CreateTriggerSkill {
  name = "#fm_jingang_skill",
  attached_equip = "fm_jingang",
  -- anim_type = "offensive",
  priority = 0,
  frequency = Skill.Compulsory,
  events = { fk.TargetSpecified, fk.DamageCaused },
  can_trigger = function(self, event, target, player, data)
    if event == fk.DamageCaused then
      return target == player and player:hasSkill(self.name) and data.to:getEquipment(Card.SubtypeArmor) and data.card and
          data.card.trueName == "slash" and not data.chain
    else
      return target == player and player:hasSkill(self.name) and data.card and data.card.trueName == "slash"
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.DamageCaused then
      data.damage = data.damage + 1
    else
      room:addPlayerMark(room:getPlayerById(data.to), fk.MarkArmorNullified)
      data.extra_data = data.extra_data or {}
      data.extra_data.vajraNullified = data.extra_data.vajraNullified or {}
      data.extra_data.vajraNullified[tostring(data.to)] = (data.extra_data.vajraNullified[tostring(data.to)] or 0) + 1
      room:notifySkillInvoked(player, self.name, "defensive")
    end
  end,

  refresh_events = { fk.CardUseFinished },
  can_refresh = function(self, event, target, player, data)
    return data.extra_data and data.extra_data.vajraNullified
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for key, num in pairs(data.extra_data.vajraNullified) do
      local p = room:getPlayerById(tonumber(key))
      if p:getMark(fk.MarkArmorNullified) > 0 then
        room:removePlayerMark(p, fk.MarkArmorNullified, num)
      end
    end

    data.vajraNullified = nil
  end,
}
Fk:addSkill(fm_jingang_Skill)

local fm_jingang = fk.CreateWeapon {
  name = "&fm_jingang",
  suit = Card.Spade,
  number = 3,
  attack_range = 3,
  equip_skill = fm_jingang_Skill,
}
extension_card:addCard(fm_jingang)
Fk:loadTranslationTable {
  ["fm_jingang"] = "伏魔金刚杵",
  [":fm_jingang"] = "装备牌·武器<br /><b>攻击范围</b>：3<br /><b>武器技能</b>：锁定技。你的【杀】无视目标角色的防具，且【杀】对有防具的目标造成的伤害+1。",
  ["#fm_jingang_skill"] = "伏魔金刚杵",
}

--神威飞将剑
local sw_feijiang_skill = fk.CreateTriggerSkill {
  name = "#sw_feijiang_skill",
  attached_equip = "sw_feijiang",
  anim_type = "drawcard",
  priority = 2,
  frequency = Skill.Compulsory,
  events = { fk.Damage },
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and
      data.card and data.card.trueName == "slash" 
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:drawCards(player,data.damage,self.name)
  end,
}
Fk:addSkill(sw_feijiang_skill)

local sw_feijiang = fk.CreateWeapon {
  name = "sw_feijiang",
  suit = Card.Spade,
  number = 6,
  attack_range = 2,
  equip_skill = sw_feijiang_skill,
}

extension_card:addCards({
  sw_feijiang,
})
Fk:loadTranslationTable {
  ["sw_feijiang"] = "神威飞将剑",
  [":sw_feijiang"] = "装备牌·武器<br /><b>攻击范围</b>：２<br /><b>武器技能</b>：每回合限一次，锁定技，当你使用【杀】对目标造成伤害后，你摸X张牌。（X为伤害值）",
  ["#sw_feijiang_skill"] = "神威飞将剑",
}
--血影刀
local xyd_xueyingdao_skill = fk.CreateTriggerSkill {
  name = "#xyd_xueyingdao_skill",
  attached_equip = "xyd_xueyingdao",
  anim_type = "offensive",
  events = { fk.DamageCaused },
  can_trigger = function(self, event, target, player, data)
    return player == target and player:hasSkill(self.name) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and
        data.card and data.card.trueName == "slash" and player:isWounded()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:recover({
      who = player,
      num = 1,
      recoverBy = player,
      skillName = self.name
    })
    -- room:notifySkillInvoked(player, self.name, "defensive")
  end,
}
Fk:addSkill(xyd_xueyingdao_skill)

local xyd_xueyingdao = fk.CreateWeapon {
  name = "xyd_xueyingdao",
  suit = Card.Club,
  number = 1,
  attack_range = 2,
  equip_skill = xyd_xueyingdao_skill,
}
extension_card:addCards({
  xyd_xueyingdao,
})
Fk:loadTranslationTable {
  ["xyd_xueyingdao"] = "血影刀",
  [":xyd_xueyingdao"] = "武器牌·武器<br /><b>攻击范围</b>：2<br /><b>武器技能</b>：每回合限一次，你使用【杀】造成伤害后，你回复1点体力。",
  ["#xyd_xueyingdao_skill"] = "血影刀",
}

--联军盛宴
local ljsySkill = fk.CreateActiveSkill{
  name = "ljsy_skill",
--   can_use = Util.GlobalCanUse,
--   on_use = Util.GlobalOnUse,
  mod_target_filter = function(self, to_select, selected, user, card, distance_limited)
    local room = Fk:currentRoom()
    local tar = room:getPlayerById(to_select)
    local carduser = room:getPlayerById(user)
    return tar and carduser and GensLimts:isSameCamp(tar,carduser)
  end,
  target_filter = function(self, to_select, selected)
    return self:modTargetFilter(to_select, selected, Self.id)
  end,

  can_use = function(self, player, card)
    for _, p in ipairs(Fk:currentRoom().alive_players) do
      if not player:isProhibited(p, card) and self:modTargetFilter(p.id, {}, player.id, card, true) then
        return true
      end
    end
  end,
  on_use = function(self, room, cardUseEvent)
    if not cardUseEvent.tos or #TargetGroup:getRealTargets(cardUseEvent.tos) == 0 then
        cardUseEvent.tos = {}
        for _, p in ipairs(room:getAlivePlayers()) do
            if not room:getPlayerById(cardUseEvent.from):isProhibited(p, cardUseEvent.card) and self:modTargetFilter(p.id, {}, cardUseEvent.from, cardUseEvent, true) then
                TargetGroup:pushTargets(cardUseEvent.tos, p.id)
            end
        end
    end
  end,
  
  on_effect = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.to)
    if player == target then
      room:drawCards(player,2,self.name)
    else
      if not target.dead and GensLimts:isSameCamp(target,player) then
        if target:isWounded() then
          room:recover({
            who = target,
            num = 1,
            recoverBy = player,
            card = effect.card,
            skillName = self.name,
          })
        else
          room:drawCards(target,1,self.name)
        end
      end
    end
  end
}
local ljsy = fk.CreateTrickCard{
  name = "ljsy",
  suit = Card.Heart,
  number = 1,
  multiple_targets = true,
  skill = ljsySkill,
}

extension_card:addCards({
  ljsy,
--   ljsy:clone(Card.Heart, 2),
--   ljsy:clone(Card.Heart, 3),
--   ljsy:clone(Card.Heart, 4),
  ljsy:clone(Card.Heart, 5),
  ljsy:clone(Card.Heart, 6),
})
Fk:loadTranslationTable {
  ["ljsy"] = "联军盛宴",
  [":ljsy"] = "锦囊牌<br /><b>时机</b>：出牌阶段<br /><b>目标</b>：所有角色<br /><b>效果</b>：摸2张牌，同势力角色回复1点体力（若满血则摸1张牌）。",
}

local rep_crossbowSkill = fk.CreateTriggerSkill{
  name = "#rep_crossbowSkill",
  attached_equip = "rep_crossbow",
  events = {fk.CardUseFinished,fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    if event == fk.CardUseFinished then
      return target == player and player:getMark("crosstatus") == 0 and player:hasSkill(self) and player.phase == Player.Play and
      data.card.trueName == "slash" and not player.dead
    else
      return player ~= target and player:hasSkill(self) and player:getMark("crosstatus") == 1
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUseFinished then
      local tos = TargetGroup:getRealTargets(data.tos)
      local tars = table.filter(tos, function(id)
        local pr = room:getPlayerById(id)
        return not pr.dead
      end)
      if #tars == 0 then 
        room:setPlayerMark(player,"crosstatus",0)
        return 
      else
        if room:askForSkillInvoke(player, self.name) then
          self.cost_data = tars
          return true
        end
      end
    else
      room:setPlayerMark(player,"crosstatus",2)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player,"crosstatus",1)
    local useslash = "slash"
    local slashatos = table.clone(self.cost_data)
    while player:getMark("crosstatus") == 1 and not player.dead do
      local tars = table.filter(slashatos, function(id)
        local pr = room:getPlayerById(id)
        return not pr.dead
      end)
      if #tars == 0 then 
        room:setPlayerMark(player,"crosstatus",0)
        return 
      end
      -- local use =room:askForUseCard(player,"slash", "slash","#repcrossbos_useslash",true,{exclusive_targets = tars})
      local usecard = nil
      for _,cid in ipairs(player.player_cards[Player.Hand]) do
        local card = Fk:getCardById(cid)
        if card.trueName == useslash then
          usecard = card
          break
        end
      end  
      if usecard then
        room:broadcastPlaySound("./packages/standard_cards/audio/card/crossbow")
        room:setEmotion(player, "./packages/standard_cards/image/anim/crossbow")
        room:useCard({
          card = usecard,
          from = player.id,
          tos = data.tos,
          skillName = self.name,
          extraUse = true,
        })
      else
        room:setPlayerMark(player,"crosstatus",0)
        return 
      end
    end
    room:setPlayerMark(player,"crosstatus",0)
  end,
}
Fk:addSkill(rep_crossbowSkill)
local rep_crossbow = fk.CreateWeapon {
  name = "rep_crossbow",
  suit = Card.Spade,
  number = 7,
  attack_range = 2,
  equip_skill = rep_crossbowSkill,
}
extension_card:addCard(rep_crossbow)
Fk:loadTranslationTable {
  ["rep_crossbow"] = "代连弩",
  ["#rep_crossbowSkill"] = "代连弩",
  ["#repcrossbos_useslash"] = "是否对目标依次使用手牌的杀？",
  [":rep_crossbow"] = "装备牌·武器<br /><b>攻击范围</b>：2<br /><b>武器技能</b>：你可以对目标依次使用手牌的杀，直到目标濒死",
}
--自定义风华绝代卡组
extension_card:addCards{
  Fk:cloneCard("slash", Card.Diamond, 1),
  Fk:cloneCard("slash", Card.Diamond, 2),
  Fk:cloneCard("slash", Card.Heart, 3),
  Fk:cloneCard("slash", Card.Heart, 4),
  Fk:cloneCard("slash", Card.Spade, 9),
  Fk:cloneCard("slash", Card.Spade, 10),
  Fk:cloneCard("slash", Card.Club, 11),
  Fk:cloneCard("slash", Card.Club, 12),

  Fk:cloneCard("thunder__slash", Card.Club, 5),
  Fk:cloneCard("thunder__slash", Card.Club, 6),
  Fk:cloneCard("fire__slash", Card.Heart, 7),
  Fk:cloneCard("fire__slash", Card.Diamond, 8),
  Fk:cloneCard("jink", Card.Diamond, 1),
  Fk:cloneCard("jink", Card.Diamond, 2),
  Fk:cloneCard("jink", Card.Heart, 3),
  Fk:cloneCard("jink", Card.Heart, 4),
  Fk:cloneCard("peach", Card.Diamond, 6),

  Fk:cloneCard("analeptic", Card.Diamond, 12),
  Fk:cloneCard("analeptic", Card.Spade, 13),
  Fk:cloneCard("spear", Card.Club, 5),
  Fk:cloneCard("axe", Card.Spade, 12),
  Fk:cloneCard("kylin_bow", Card.Diamond, 8),
  Fk:cloneCard("guding_blade", Card.Diamond, 4),
  Fk:cloneCard("chitu", Card.Club, 1),
  Fk:cloneCard("jueying", Card.Spade, 9),

  Fk:cloneCard("snatch", Card.Diamond, 7),
  Fk:cloneCard("snatch", Card.Spade, 9),
  Fk:cloneCard("dismantlement", Card.Club, 5),
  Fk:cloneCard("dismantlement", Card.Spade, 4),
  -- Fk:cloneCard("dismantlement", Card.Heart, 2),
  Fk:cloneCard("amazing_grace", Card.Club, 6),
  -- Fk:cloneCard("amazing_grace", Card.Heart, 4),
  Fk:cloneCard("duel", Card.Diamond, 1),
  Fk:cloneCard("duel", Card.Spade, 1),
  Fk:cloneCard("savage_assault", Card.Club, 7),
  Fk:cloneCard("archery_attack", Card.Diamond, 1),
  -- Fk:cloneCard("lightning", Card.Heart, 12),
  Fk:cloneCard("god_salvation", Card.Diamond, 6),
  Fk:cloneCard("nullification", Card.Club, 12),
  -- Fk:cloneCard("nullification", Card.Club, 13),
  Fk:cloneCard("nullification", Card.Spade, 11),
  -- Fk:cloneCard("nullification", Card.Diamond, 12),
  -- Fk:cloneCard("nullification", Card.Heart, 1),
  -- Fk:cloneCard("nullification", Card.Spade, 13),
  Fk:cloneCard("nullification", Card.Club, 7),
  -- Fk:cloneCard("indulgence", Card.Heart, 6),
  Fk:cloneCard("indulgence", Card.Club, 6),
  -- Fk:cloneCard("indulgence", Card.Spade, 6),
  Fk:cloneCard("iron_chain", Card.Spade, 5),
  -- Fk:cloneCard("iron_chain", Card.Club, 12),
  -- Fk:cloneCard("iron_chain", Card.Club, 13),
  Fk:cloneCard("supply_shortage", Card.Spade, 10),
  -- Fk:cloneCard("supply_shortage", Card.Club, 4),
}

Fk:addMiniGame{
  name = "mutyselchc",
  qml_path = "packages/lang/qml/MutyDetailedCheckBox",
  default_choice = function(player, data)
    return {data.choices[1]}
  end,
  update_func = function(player, data)
    local room = player.room
    for _,pr in ipairs(room.players) do
      if pr.id > 0 and pr ~= player and pr.mini_game_data then
        pr:doNotify("UpdateMiniGame", json.encode(data))
      end
    end
  end,
}

Fk:addMiniGame{
  name = "mobileselgens",
  qml_path = "packages/lang/qml/MobilleAllPlayersSelGenBox",
  default_choice = function(player, data)
    return data.gens[1]
  end,
  update_func = function(player, data)
    local room = player.room
    -- local d = player.mini_game_data.data
    for _,pr in ipairs(room.players) do
      if pr.id > 0 and pr ~= player and pr.mini_game_data then
        -- local friend = pr
        pr:doNotify("UpdateMiniGame", json.encode(data))
      end
    end
  end,
}

Fk:addMiniGame {
  name = "GeneralCanChangeForWDTX",
  qml_path = "packages/lang/qml/ChooseGeneralWithCanChange",
  default_choice = function(player, data) --默认值
    return table.random(data.cards, data.num)
  end,
  update_func = function(player, data)
    player:doNotify("UpdateMiniGame", json.encode(data))
  end,
}

--虎牢关、无尽的试炼模式
-- Fk:addGameMode(require "packages/lang/hulao_mode")
-- Fk:addGameMode(require "packages/lang/wujinshilian_mode")
-- Fk:addGameMode(require "packages/lang/ZSHH_mode")
-- Fk:addGameMode(require "packages/lang/joyKJ_mode")
-- Fk:addGameMode(require "packages/lang/qyUnion")
Fk:addGameMode(require "packages/lang/XLKJ_mode")
Fk:addGameMode(require "packages/lang/NorKJ_mode")
Fk:addGameMode(require "packages/lang/MoNvKJ_mode")
Fk:addGameMode(require "packages/lang/doubleKJ_mode")
Fk:addGameMode(require "packages/lang/doudizhuKJ_mode")
Fk:addGameMode(require "packages/lang/threeKJ_mode")
Fk:addGameMode(require "packages/lang/threeMobileKJ_mode")

return {extension,
        extension_card
}
